]> git.donarmstrong.com Git - lilypond.git/blob - lily/general-scheme.cc
Split WWW target in two stages WWW-1 and WWW-2
[lilypond.git] / lily / general-scheme.cc
1 /*
2   lily-guile.cc -- implement assorted Guile bindings
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 1998--2007 Jan Nieuwenhuizen <janneke@gnu.org>
7   Han-Wen Nienhuys <hanwen@xs4all.nl>
8 */
9
10 #include "config.hh"
11
12 #include <cstdio>
13 #include <ctype.h>
14 #include <cstring>  /* memset */
15 using namespace std;
16
17 #include "international.hh"
18 #include "libc-extension.hh"
19 #include "lily-guile.hh"
20 #include "misc.hh"
21 #include "warn.hh"
22 #include "version.hh"
23 #include "dimensions.hh"
24 #include "main.hh"
25 #include "file-path.hh"
26 #include "relocate.hh"
27 #include "file-name.hh"
28 #include "string-convert.hh"
29
30 LY_DEFINE (ly_start_environment, "ly:start-environment",
31            0, 0, 0, (),
32            "Return the environment (a list of strings) that was in"
33            " effect at program start.")
34 {
35   SCM l = SCM_EOL;
36   SCM *tail = &l;
37
38   for (vsize i = 0; i < start_environment_global.size (); i++)
39     {
40       *tail = scm_cons (ly_string2scm (start_environment_global[i]),
41                         SCM_EOL);
42       tail = SCM_CDRLOC(*tail);
43     }
44
45   return l;
46 }
47
48
49 LY_DEFINE (ly_find_file, "ly:find-file",
50            1, 0, 0, (SCM name),
51            "Return the absolute file name of @var{name},"
52            " or @code{#f} if not found.")
53 {
54   LY_ASSERT_TYPE (scm_is_string, name, 1);
55
56   string nm = ly_scm2string (name);
57   string file_name = global_path.find (nm);
58   if (file_name.empty ())
59     return SCM_BOOL_F;
60
61   return ly_string2scm (file_name);
62 }
63
64 /*
65   Ugh. Gulped file is copied twice. (maybe thrice if you count stdio
66   buffering.)
67 */
68 LY_DEFINE (ly_gulp_file, "ly:gulp-file",
69            1, 1, 0, (SCM name, SCM size),
70            "Read the file @var{name}, and return its contents in a string."
71            "  The file is looked up using the search path.")
72 {
73   LY_ASSERT_TYPE (scm_is_string, name, 1);
74   int sz = INT_MAX;
75   if (size != SCM_UNDEFINED)
76     {
77       LY_ASSERT_TYPE (scm_is_number, size, 2);
78       sz = scm_to_int (size);
79     }
80   
81   string contents = gulp_file_to_string (ly_scm2string (name), true, sz);
82   return scm_from_locale_stringn (contents.c_str (), contents.length ());
83 }
84
85 LY_DEFINE (ly_error, "ly:error",
86            1, 0, 1, (SCM str, SCM rest),
87            "A Scheme callable function to issue the error @var{str}."
88            "  The error is formatted with @code{format} and @var{rest}.")
89 {
90   LY_ASSERT_TYPE (scm_is_string, str, 1);
91   str = scm_simple_format (SCM_BOOL_F, str, rest);
92   error (ly_scm2string (str));
93   return SCM_UNSPECIFIED;
94 }
95
96 LY_DEFINE (ly_message, "ly:message",
97            1, 0, 1, (SCM str, SCM rest),
98            "A Scheme callable function to issue the message @var{str}."
99            "  The message is formatted with @code{format} and @var{rest}.")
100 {
101   LY_ASSERT_TYPE (scm_is_string, str, 1);
102   str = scm_simple_format (SCM_BOOL_F, str, rest);
103   message (ly_scm2string (str));
104   return SCM_UNSPECIFIED;
105 }
106
107 LY_DEFINE (ly_progress, "ly:progress",
108            1, 0, 1, (SCM str, SCM rest),
109            "A Scheme callable function to print progress @var{str}."
110            "  The message is formatted with @code{format} and @var{rest}.")
111 {
112   LY_ASSERT_TYPE (scm_is_string, str, 1);
113   str = scm_simple_format (SCM_BOOL_F, str, rest);
114   progress_indication (ly_scm2string (str));
115   return SCM_UNSPECIFIED;
116 }
117
118 LY_DEFINE (ly_programming_error, "ly:programming-error",
119            1, 0, 1, (SCM str, SCM rest),
120            "A Scheme callable function to issue the internal warning"
121            "  @var{str}.  The message is formatted with @code{format}"
122            " and @var{rest}.")
123 {
124   LY_ASSERT_TYPE (scm_is_string, str, 1);
125   str = scm_simple_format (SCM_BOOL_F, str, rest);
126   programming_error (ly_scm2string (str));
127   return SCM_UNSPECIFIED;
128 }
129
130 LY_DEFINE (ly_warning, "ly:warning",
131            1, 0, 1, (SCM str, SCM rest),
132            "A Scheme callable function to issue the warning @code{str}."
133            "  The message is formatted with @code{format} and @code{rest}.")
134 {
135   LY_ASSERT_TYPE (scm_is_string, str, 1);
136   str = scm_simple_format (SCM_BOOL_F, str, rest);
137   warning (ly_scm2string (str));
138   return SCM_UNSPECIFIED;
139 }
140
141 LY_DEFINE (ly_dir_p, "ly:dir?",
142            1, 0, 0, (SCM s),
143            "A type predicate.  The direction@tie{}@code{s} is @code{-1},"
144            " @code{0} or@tie{}@code{1}, where @code{-1} represents"
145            " left or down and @code{1} represents right or up.")
146 {
147   if (scm_is_number (s))
148     {
149       int i = scm_to_int (s);
150       return (i >= -1 && i <= 1) ? SCM_BOOL_T : SCM_BOOL_F;
151     }
152   return SCM_BOOL_F;
153 }
154
155 LY_DEFINE (ly_assoc_get, "ly:assoc-get",
156            2, 1, 0,
157            (SCM key, SCM alist, SCM default_value),
158            "Return value if @var{key} in @var{alist}, else @code{default-value}"
159            " (or @code{#f} if not specified).")
160 {
161   LY_ASSERT_TYPE(ly_cheap_is_list, alist, 2);
162   
163   SCM handle = scm_assoc (key, alist);
164   if (scm_is_pair (handle))
165     return scm_cdr (handle);
166   
167   if (default_value == SCM_UNDEFINED)
168     default_value = SCM_BOOL_F;
169
170   return default_value;
171 }
172
173 LY_DEFINE (ly_string_substitute, "ly:string-substitute",
174            3, 0, 0, (SCM a, SCM b, SCM s),
175            "Replace string@tie{}@var{a} by string@tie{}@var{b} in"
176            " string@tie{}@var{s}.")
177 {
178   LY_ASSERT_TYPE (scm_is_string, s, 1);
179   LY_ASSERT_TYPE (scm_is_string, b, 2);
180   LY_ASSERT_TYPE (scm_is_string, s, 3);
181
182   string ss = ly_scm2string (s);
183   replace_all (ss, string (scm_i_string_chars (a)),
184                    string (scm_i_string_chars (b)));
185   return ly_string2scm (ss);
186 }
187   
188 LY_DEFINE (ly_number_2_string, "ly:number->string",
189            1, 0, 0, (SCM s),
190            "Convert @var{num} to a string without generating many decimals.")
191 {
192   LY_ASSERT_TYPE (scm_is_number, s, 1);
193
194   char str[400];                        // ugh.
195
196   if (scm_exact_p (s) == SCM_BOOL_F)
197     {
198       Real r (scm_to_double (s));
199         if (isinf (r) || isnan (r))
200           {
201             programming_error (_ ("infinity or NaN encountered while converting Real number"));
202             programming_error (_ ("setting to zero"));
203
204             r = 0.0;
205           }
206
207       snprintf (str, sizeof (str), "%.4f", r);
208     }
209   else
210     snprintf (str, sizeof (str), "%d", int (scm_to_int (s)));
211
212   return scm_from_locale_string (str);
213 }
214
215 LY_DEFINE (ly_version, "ly:version", 0, 0, 0, (),
216            "Return the current lilypond version as a list, e.g.,"
217            " @code{(1 3 127 uu1)}.")
218 {
219   char const *vs = "\'(" MAJOR_VERSION " " MINOR_VERSION " " PATCH_LEVEL " " MY_PATCH_LEVEL ")";
220
221   return scm_c_eval_string ((char *)vs);
222 }
223
224 LY_DEFINE (ly_unit, "ly:unit", 0, 0, 0, (),
225            "Return the unit used for lengths as a string.")
226 {
227   return scm_from_locale_string (INTERNAL_UNIT);
228 }
229
230 LY_DEFINE (ly_dimension_p, "ly:dimension?", 1, 0, 0, (SCM d),
231            "Return @var{d} as a number.  Used to distinguish length"
232            " variables from normal numbers.")
233 {
234   return scm_number_p (d);
235 }
236
237 /*
238   Debugging mem leaks:
239 */
240 LY_DEFINE (ly_protects, "ly:protects",
241            0, 0, 0, (),
242            "Return hash of protected objects.")
243 {
244   return scm_protects;
245 }
246
247 LY_DEFINE (ly_gettext, "ly:gettext",
248            1, 0, 0, (SCM string),
249            "A Scheme wrapper function for @code{gettext}.")
250 {
251   LY_ASSERT_TYPE (scm_is_string, string, 1);
252   return ly_string2scm (_ (scm_i_string_chars (string)));
253 }
254
255 LY_DEFINE (ly_output_formats, "ly:output-formats",
256            0, 0, 0, (),
257            "Formats passed to @option{--format} as a list of strings,"
258            " used for the output.")
259 {
260   vector<string> output_formats = string_split (output_format_global, ',');
261
262   SCM lst = SCM_EOL;
263   int output_formats_count = output_formats.size ();
264   for (int i = 0; i < output_formats_count; i++)
265     lst = scm_cons (ly_string2scm (output_formats[i]), lst);
266
267   return lst;
268 }
269
270 LY_DEFINE (ly_wide_char_2_utf_8, "ly:wide-char->utf-8",
271            1, 0, 0, (SCM wc),
272            "Encode the Unicode codepoint @var{wc}, an integer, as UTF-8.")
273 {
274   char buf[5];
275
276   LY_ASSERT_TYPE (scm_is_integer, wc, 1);
277   unsigned wide_char = (unsigned) scm_to_int (wc);
278   char *p = buf;
279
280   if (wide_char < 0x0080)
281     *p++ = (char)wide_char;
282   else if (wide_char < 0x0800)
283     {
284       *p++ = (char) (((wide_char >> 6)) | 0xC0);
285       *p++ = (char) (((wide_char) & 0x3F) | 0x80);
286     }
287   else if (wide_char < 0x10000)
288     {
289       *p++ = (char) (((wide_char >> 12)) | 0xE0);
290       *p++ = (char) (((wide_char >> 6) & 0x3F) | 0x80);
291       *p++ = (char) (((wide_char) & 0x3F) | 0x80);
292     }
293   else
294     {
295       *p++ = (char) (((wide_char >> 18)) | 0xF0);
296       *p++ = (char) (((wide_char >> 12) & 0x3F) | 0x80);
297       *p++ = (char) (((wide_char >> 6) & 0x3F) | 0x80);
298       *p++ = (char) (((wide_char) & 0x3F) | 0x80);
299     }
300   *p = 0;
301
302   return scm_from_locale_string (buf);
303 }
304
305 LY_DEFINE (ly_effective_prefix, "ly:effective-prefix",
306            0, 0, 0, (),
307            "Return effective prefix.")
308 {
309   return ly_string2scm (lilypond_datadir);
310 }
311
312 LY_DEFINE (ly_chain_assoc_get, "ly:chain-assoc-get",
313            2, 1, 0, (SCM key, SCM achain, SCM dfault),
314            "Return value for @var{key} from a list of alists @var{achain}."
315            "  If no entry is found, return @var{dfault} or @code{#f} if no"
316            " @var{dfault} is specified.")
317 {
318   if (scm_is_pair (achain))
319     {
320       SCM handle = scm_assoc (key, scm_car (achain));
321       if (scm_is_pair (handle))
322         return scm_cdr (handle);
323       else
324         return ly_chain_assoc_get (key, scm_cdr (achain), dfault);
325     }
326   return dfault == SCM_UNDEFINED ? SCM_BOOL_F : dfault;
327 }
328
329
330 LY_DEFINE (ly_stderr_redirect, "ly:stderr-redirect",
331            1, 1, 0, (SCM file_name, SCM mode),
332            "Redirect stderr to @var{file-name}, opened with @var{mode}.")
333 {
334   LY_ASSERT_TYPE (scm_is_string, file_name, 1);
335
336   string m = "w";
337   if (mode != SCM_UNDEFINED && scm_string_p (mode))
338     m = ly_scm2string (mode);
339   /* dup2 and (fileno (current-error-port)) do not work with mingw'c
340      gcc -mwindows.  */
341   fflush (stderr); 
342   freopen (ly_scm2string (file_name).c_str (), m.c_str (), stderr);
343   return SCM_UNSPECIFIED;
344 }
345
346 static SCM
347 accumulate_symbol (void *closure, SCM key, SCM val, SCM result)
348 {
349   (void) closure;
350   (void) val;
351   return scm_cons (key, result);
352 }
353
354 LY_DEFINE (ly_hash_table_keys, "ly:hash-table-keys",
355           1,0,0, (SCM tab),
356           "Return a list of keys in @var{tab}.")
357 {
358   return scm_internal_hash_fold ((Hash_closure_function) & accumulate_symbol,
359                                  NULL, SCM_EOL, tab);
360 }
361
362 LY_DEFINE (ly_camel_case_2_lisp_identifier, "ly:camel-case->lisp-identifier",
363            1, 0, 0, (SCM name_sym),
364            "Convert @code{FooBar_Bla} to @code{foo-bar-bla} style symbol.")
365 {
366   LY_ASSERT_TYPE (ly_is_symbol, name_sym, 1);
367   
368   /*
369     TODO: should use strings instead?
370   */
371   
372   const string in = ly_symbol2string (name_sym);
373   string result = camel_case_to_lisp_identifier (in);
374
375   return ly_symbol2scm (result.c_str ());
376 }
377
378 LY_DEFINE (ly_expand_environment, "ly:expand-environment",
379            1, 0, 0, (SCM str),
380            "Expand @code{$VAR} and @code{$@{VAR@}} in @var{str}.")
381 {
382   LY_ASSERT_TYPE (scm_is_string, str, 1);
383
384   return ly_string2scm (expand_environment_variables (ly_scm2string (str)));
385 }
386                  
387
388 LY_DEFINE (ly_truncate_list_x, "ly:truncate-list!",
389            2, 0, 0, (SCM lst, SCM i),
390            "Take at most the first @var{i} of list @var{lst}.")
391 {
392   LY_ASSERT_TYPE (scm_is_integer, i, 1);
393
394   int k = scm_to_int (i);
395   if (k == 0)
396     lst = SCM_EOL;
397   else
398     {
399       SCM s = lst;
400       k--;
401       for (; scm_is_pair (s) && k--; s = scm_cdr (s))
402         ;
403
404       if (scm_is_pair (s))
405         scm_set_cdr_x (s, SCM_EOL);
406     }
407   return lst;
408 }
409
410 string
411 format_single_argument (SCM arg, int precision)
412 {
413   if (scm_is_integer (arg) && scm_exact_p (arg) == SCM_BOOL_T)
414     return (String_convert::int_string (scm_to_int (arg)));
415   else if (scm_is_number (arg))
416     {
417       Real val = scm_to_double (arg);
418
419       if (isnan (val) || isinf (val))
420         {
421           warning (_ ("Found infinity or nan in output. Substituting 0.0"));
422           return ("0.0");
423           if (strict_infinity_checking)
424             abort ();
425         }
426       else
427         return (String_convert::form_string ("%.*lf", precision, val));
428     }
429   else if (scm_is_string (arg))
430     return (ly_scm2string (arg));
431   else if (scm_is_symbol (arg))
432     return (ly_symbol2string (arg));
433   else
434     {
435       ly_progress (scm_from_locale_string ("Unsupported SCM value for format: ~a"),
436                    scm_list_1 (arg));
437     }
438   
439     
440   return "";    
441 }
442
443 LY_DEFINE (ly_format, "ly:format",
444            1, 0, 1, (SCM str, SCM rest),
445            "LilyPond specific format, supporting @code{~a} and @code{~[0-9]f}.")
446 {
447   LY_ASSERT_TYPE (scm_is_string, str, 1);
448
449   string format = ly_scm2string (str);
450   vector<string> results;
451
452   vsize i = 0;
453   while (i < format.size ())
454     {
455       vsize tilde = format.find ('~', i);
456
457       results.push_back (format.substr (i, (tilde-i)));
458
459       if (tilde == NPOS)
460         break ;
461       
462       tilde ++;
463
464       char spec = format.at (tilde ++);
465       if (spec == '~')
466         results.push_back ("~");
467       else
468         {
469           if (!scm_is_pair (rest))
470             {
471               programming_error (string (__FUNCTION__) 
472                                  + ": not enough arguments for format.");
473               return ly_string2scm ("");
474             }
475           
476           SCM arg = scm_car (rest);
477           rest = scm_cdr (rest);
478
479           int precision = 8;
480           
481           if (spec == '$')
482             precision = 2;
483           else if (isdigit (spec))
484             {
485               precision = spec - '0';
486               spec = format.at (tilde ++);
487             }
488                    
489           if (spec == 'a' || spec == 'A' || spec == 'f' || spec == '$')
490             results.push_back (format_single_argument (arg, precision));
491           else if (spec == 'l')
492             {
493               SCM s = arg;
494               for (; scm_is_pair (s); s = scm_cdr (s))
495                 {
496                   results.push_back (format_single_argument (scm_car (s), precision));
497                   if (scm_cdr (s) != SCM_EOL)
498                     results.push_back (" ");
499                 }
500
501               if (s != SCM_EOL)
502                 results.push_back (format_single_argument (s, precision));
503                 
504             }
505         }
506
507       i = tilde;
508     }
509
510   if (scm_is_pair (rest))
511     programming_error (string (__FUNCTION__)
512                        + ": too many  arguments");
513
514   vsize len = 0;
515   for (vsize i = 0; i < results.size (); i++)
516     len += results[i].size ();
517   
518   char *result = (char*) scm_malloc (len + 1);
519   char *ptr = result;
520   for (vsize i = 0; i < results.size (); i++)
521     {
522       strncpy (ptr, results[i].c_str (), results[i].size ());
523       ptr += results[i].size ();
524     }
525   *ptr = '\0';
526     
527   return scm_take_locale_stringn (result, len);
528 }