]> git.donarmstrong.com Git - lilypond.git/blob - lily/lily-guile.cc
* lily/include/lily-guile.hh: compatibility glue for 1.6
[lilypond.git] / lily / lily-guile.cc
1 /*
2   lily-guile.cc -- implement assorted guile functions
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 1998--2004 Jan Nieuwenhuizen <janneke@gnu.org>
7                  Han-Wen Nienhuys <hanwen@cs.uu.nl>
8 */
9
10
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <libintl.h>            // gettext on macos x
14 #include <math.h>   /* isinf */
15 #include <string.h> /* strdup, strchr */
16 #include <ctype.h>
17
18 #include "lily-proto.hh"
19 #include "version.hh"
20
21 /* MacOS S fix:
22    source-file.hh includes cmath which undefines isinf and isnan
23
24    FIXME: #ifdef MACOS_X?
25 */
26 inline int my_isinf (Real r) { return isinf (r); }
27 inline int my_isnan (Real r) { return isnan (r); }
28
29
30 #include "libc-extension.hh"
31 #include "lily-guile.hh"
32 #include "main.hh"
33 #include "file-path.hh"
34 #include "warn.hh"
35 #include "direction.hh"
36 #include "offset.hh"
37 #include "interval.hh"
38 #include "pitch.hh"
39 #include "dimensions.hh"
40 #include "source-file.hh"
41
42 // #define TEST_GC
43
44 SCM
45 ly_last (SCM list)
46 {
47   return ly_car (scm_last_pair (list));
48 }
49
50
51 SCM
52 ly_write2scm (SCM s)
53 {
54   SCM port = scm_mkstrport (SCM_INUM0, 
55                             scm_make_string (SCM_INUM0, SCM_UNDEFINED),
56                             SCM_OPN | SCM_WRTNG,
57                             "ly_write2string");
58   //  SCM write = scm_eval_3 (ly_symbol2scm ("write"), s, SCM_EOL);
59   SCM write = scm_primitive_eval (ly_symbol2scm ("write"));
60   
61   // scm_apply (write, port, SCM_EOL);
62   scm_call_2 (write, s, port);
63   return scm_strport_to_string (port);
64 }
65
66
67 SCM
68 ly_quote_scm (SCM s)
69 {
70   return scm_list_n (ly_symbol2scm ("quote"), s, SCM_UNDEFINED);
71 }
72
73 String
74 ly_symbol2string (SCM s)
75 {
76   /*
77     Ugh. this is not very efficient.
78    */
79   SCM str = scm_symbol_to_string (s);
80   return ly_scm2string (str);
81 }
82
83 String
84 gulp_file_to_string (String fn)
85 {
86   String s = global_path.find (fn);
87   if (s == "")
88     {
89       String e = _f ("can't find file: `%s'", fn);
90       e += " ";
91       e += _f ("(load path: `%s')", global_path.to_string ());
92       error (e);
93     }
94   else if (verbose_global_b)
95     progress_indication ("[" + s);
96
97   int n;
98   char * str = gulp_file (s, &n);
99   String result (str);
100   delete[] str;
101   
102   if (verbose_global_b)
103     progress_indication ("]");
104
105   return result;
106 }
107
108 LY_DEFINE (ly_gulp_file, "ly:gulp-file",
109            1, 0, 0, (SCM name),
110            "Read the file @var{name}, and return its contents in a string.  "
111            "The file is looked up using the search path.")
112 {
113   SCM_ASSERT_TYPE (scm_is_string (name), name, SCM_ARG1, __FUNCTION__, "string");
114   return scm_makfrom0str (gulp_file_to_string (ly_scm2string (name)).to_str0 ());
115 }
116
117
118 extern "C" {
119   // maybe gdb 5.0 becomes quicker if it doesn't do fancy C++ typing?
120 void
121 ly_display_scm (SCM s)
122 {
123   scm_display (s, scm_current_output_port ());
124   scm_newline (scm_current_output_port ());
125 }
126 };
127
128 String
129 ly_scm2string (SCM str)
130 {
131   return String ((Byte*)scm_i_string_chars (str),
132                  (int) scm_i_string_length (str));
133 }
134
135 char *
136 ly_scm2newstr (SCM str, size_t *lenp)
137 {
138   SCM_ASSERT_TYPE (scm_is_string (str), str, SCM_ARG1, __FUNCTION__, "string");
139
140   size_t len = SCM_STRING_LENGTH (str);
141   if (char *new_str = (char *) malloc ((len + 1) * sizeof (char)))
142     {
143       memcpy (new_str, scm_i_string_chars (str), len);
144       new_str[len] = '\0';
145
146       if (lenp)
147         *lenp = len;
148       
149       return new_str;
150     }
151   return 0;
152 }
153
154 SCM
155 index_get_cell (SCM s, Direction d)
156 {
157   
158   assert (d);
159   return (d == LEFT) ? ly_car (s) : ly_cdr (s);
160 }
161
162 SCM
163 index_set_cell (SCM s, Direction d, SCM v)
164 {
165   if (d == LEFT)
166     scm_set_car_x (s, v);
167   else if (d == RIGHT)
168     scm_set_cdr_x (s, v);
169   return s;
170 }
171   
172 LY_DEFINE (ly_warn, "ly:warn",
173            1, 0, 1, (SCM str, SCM rest),
174            "Scheme callable function to issue the warning @code{msg}. "
175            "The message is formatted with @code{format} and @code{rest}.")
176 {
177   SCM_ASSERT_TYPE (scm_is_string (str), str, SCM_ARG1, __FUNCTION__, "string");
178   progress_indication ("\n");
179
180   str = scm_simple_format (SCM_BOOL_F, str, rest);
181   warning ("lily-guile: " + ly_scm2string (str));
182   return SCM_UNSPECIFIED;
183 }
184
185 LY_DEFINE (ly_programming_error, "ly:programming-error",
186            1, 0, 1, (SCM str, SCM rest),
187            "Scheme callable function to issue the warning @code{msg}. "
188            "The message is formatted with @code{format} and @code{rest}.")
189 {
190   SCM_ASSERT_TYPE (scm_is_string (str), str, SCM_ARG1, __FUNCTION__, "string");
191   progress_indication ("\n");
192
193   str = scm_simple_format (SCM_BOOL_F, str, rest);
194   programming_error (ly_scm2string (str));
195   return SCM_UNSPECIFIED;
196 }
197
198 LY_DEFINE (ly_dir_p, "ly:dir?",
199            1, 0, 0, (SCM s),
200           "type predicate. A direction is @code{-1}, @code{0} or "
201            "@code{1}, where @code{-1} represents "
202           "left or down and @code{1} represents right or up.")
203 {
204   if (ly_c_number_p (s))
205     {
206       int i = ly_scm2int (s);
207       return (i>= -1 && i <= 1)  ? SCM_BOOL_T : SCM_BOOL_F; 
208     }
209   return SCM_BOOL_F;
210 }
211
212 bool
213 is_number_pair (SCM p)
214 {
215   return ly_c_pair_p (p)
216     && ly_c_number_p (ly_car (p)) && ly_c_number_p (ly_cdr (p));
217 }
218
219 typedef void (*Void_fptr) ();
220 Array<Void_fptr> *scm_init_funcs_;
221
222 void add_scm_init_func (void (*f) ())
223 {
224   if (!scm_init_funcs_)
225     scm_init_funcs_ = new Array<Void_fptr>;
226
227   scm_init_funcs_->push (f);
228 }
229
230 void
231 ly_init_ly_module (void *)
232 {
233   for (int i=scm_init_funcs_->size () ; i--;)
234     (scm_init_funcs_->elem (i)) ();
235
236   if (verbose_global_b)
237     progress_indication ("\n");
238   
239   scm_primitive_load_path (scm_makfrom0str ("lily.scm"));
240 }
241
242 SCM global_lily_module;
243
244 void
245 ly_c_init_guile ()
246 {
247   global_lily_module = scm_c_define_module ("lily", ly_init_ly_module, 0);
248   scm_c_use_module ("lily");
249 }
250
251 unsigned int
252 ly_scm_hash (SCM s)
253 {
254   return scm_ihashv (s, ~1u);
255 }
256
257 bool
258 is_direction (SCM s)
259 {
260   if (ly_c_number_p (s))
261     {
262       int i = ly_scm2int (s);
263       return i>= -1 && i <= 1; 
264     }
265   return false;
266 }
267
268 bool
269 is_axis (SCM s)
270 {
271   if (ly_c_number_p (s))
272     {
273       int i = ly_scm2int (s);
274       return i== 0 || i == 1;
275     }
276   return false;
277 }
278
279 Direction
280 to_dir (SCM s)
281 {
282   return scm_is_integer (s) ? (Direction) ly_scm2int (s) : CENTER;
283 }
284
285 Interval
286 ly_scm2interval (SCM p)
287 {
288   return Interval (ly_scm2double (ly_car (p)), ly_scm2double (ly_cdr (p)));
289 }
290
291 Drul_array<Real>
292 ly_scm2realdrul (SCM p)
293 {
294   return Drul_array<Real> (ly_scm2double (ly_car (p)),
295                            ly_scm2double (ly_cdr (p)));
296 }
297
298 SCM
299 ly_interval2scm (Drul_array<Real> i)
300 {
301   return scm_cons (scm_make_real (i[LEFT]), scm_make_real (i[RIGHT]));
302 }
303
304 bool
305 to_boolean (SCM s)
306 {
307   return ly_c_boolean_p (s) && ly_scm2bool (s);
308 }
309
310 /* Appendable list L: the cdr contains the list, the car the last cons
311    in the list.  */
312 SCM
313 appendable_list ()
314 {
315   SCM s = scm_cons (SCM_EOL, SCM_EOL);
316   scm_set_car_x (s, s);
317   
318   return s;
319 }
320
321 void
322 appendable_list_append (SCM l, SCM elt)
323 {
324   SCM newcons = scm_cons (elt, SCM_EOL);
325   
326   scm_set_cdr_x (ly_car (l), newcons);      
327   scm_set_car_x (l, newcons);
328 }
329
330 SCM
331 ly_offset2scm (Offset o)
332 {
333   return scm_cons (scm_make_real (o[X_AXIS]), scm_make_real (o[Y_AXIS]));
334 }
335
336 Offset
337 ly_scm2offset (SCM s)
338 {
339   return Offset (ly_scm2double (ly_car (s)),
340                  ly_scm2double (ly_cdr (s)));
341 }
342
343 LY_DEFINE (ly_number2string, "ly:number->string",
344            1, 0, 0, (SCM s),
345            "Convert @var{num} to a string without generating many decimals.")
346 {
347   SCM_ASSERT_TYPE (ly_c_number_p (s), s, SCM_ARG1, __FUNCTION__, "number");
348
349   char str[400];                        // ugh.
350
351   if (scm_exact_p (s) == SCM_BOOL_F)
352     {
353       Real r (ly_scm2double (s));
354
355       if (my_isinf (r) || my_isnan (r))
356         {
357           programming_error ("Infinity or NaN encountered while converting Real number; setting to zero.");
358           r = 0.0;
359         }
360
361       sprintf (str, "%08.4f", r);
362     }
363   else
364     sprintf (str, "%d", ly_scm2int (s));
365
366   return scm_makfrom0str (str);
367 }
368
369
370
371 LY_DEFINE (ly_version,  "ly:version", 0, 0, 0, (),
372           "Return the current lilypond version as a list, e.g. @code{(1 3 127 uu1)}. ")
373 {
374   char const* vs = "\'(" MAJOR_VERSION " " MINOR_VERSION " "  PATCH_LEVEL " " MY_PATCH_LEVEL ")" ;
375   
376   return scm_c_eval_string ((char*)vs);
377 }
378
379 LY_DEFINE (ly_unit,  "ly:unit", 0, 0, 0, (),
380           "Return the unit used for lengths as a string.")
381 {
382   return scm_makfrom0str (INTERNAL_UNIT);
383 }
384
385
386
387 LY_DEFINE (ly_dimension_p,  "ly:dimension?", 1, 0, 0, (SCM d),
388           "Return @var{d} is a number. Used to distinguish length "
389           "variables from normal numbers.")
390 {
391   return scm_number_p (d);
392 }
393
394 SCM
395 ly_deep_copy (SCM src)
396 {
397   if (ly_c_pair_p (src))
398     return scm_cons (ly_deep_copy (ly_car (src)), ly_deep_copy (ly_cdr (src)));
399   else if (ly_c_vector_p (src))
400     {
401       int len = SCM_VECTOR_LENGTH (src);
402       SCM nv = scm_c_make_vector (len, SCM_UNDEFINED);
403       for (int i  =0 ; i < len ; i++)
404         {
405           SCM si = scm_int2num (i);
406           scm_vector_set_x (nv, si, ly_deep_copy (scm_vector_ref (src, si))); 
407         }
408     }
409   return src;
410 }
411
412
413
414
415 SCM
416 ly_assoc_chain (SCM key, SCM achain)
417 {
418   if (ly_c_pair_p (achain))
419     {
420       SCM handle = scm_assoc (key, ly_car (achain));
421       if (ly_c_pair_p (handle))
422         return handle;
423       else
424         return ly_assoc_chain (key, ly_cdr (achain));
425     }
426   else
427     return SCM_BOOL_F;
428 }
429
430 /* looks the key up in the cdrs of the alist-keys
431    - ignoring the car and ignoring non-pair keys.
432    Returns first match found, i.e.
433
434    alist = ((1 . 10)
435                    ((1 . 2) . 11)
436                    ((2 . 1) . 12)
437                    ((3 . 0) . 13)
438                    ((4 . 1) . 14) )
439
440 I would like (ly_assoc_cdr 1) to return 12 - because it's the first
441 element with the cdr of the key = 1.  In other words (alloc_cdr key)
442 corresponds to call
443
444 (alloc (anything . key))
445
446
447
448 */
449 SCM
450 ly_assoc_cdr (SCM key, SCM alist)
451 {
452   if (ly_c_pair_p (alist))
453     {
454       SCM trykey = ly_caar (alist);
455       if (ly_c_pair_p (trykey) && to_boolean (scm_equal_p (key, ly_cdr (trykey))))
456         return ly_car (alist);
457       else
458         return ly_assoc_cdr (key, ly_cdr (alist));
459     }
460   return SCM_BOOL_F;
461 }
462
463 /* LST has the form "sym1 sym2 sym3\nsym4\nsym5"
464    i.e. \n and ' ' can be used interchangeably as separators.  */
465 SCM
466 parse_symbol_list (char const *lst)
467 {
468   char *s = strdup (lst);
469   char *orig = s;
470   SCM create_list = SCM_EOL;
471
472   char * e = s + strlen (s) - 1;
473   while (e >= s && isspace (*e))
474     *e-- = 0;
475
476   for (char * p = s; *p; p++)
477     if (*p == '\n')
478       *p = ' ';
479   
480   if (!s[0])
481     s = 0;
482   
483   while (s)
484     {
485       char *next = strchr (s, ' ');
486       if (next)
487         *next++ = 0;
488
489       create_list = scm_cons (ly_symbol2scm (s), create_list);
490       s = next;
491     }
492
493   free (orig);
494   return create_list;
495 }
496
497 SCM
498 ly_truncate_list (int k, SCM lst)
499 {
500   if (k == 0)
501     lst = SCM_EOL;
502   else
503     {
504       SCM s = lst;
505       k--;
506       for (; ly_c_pair_p (s) && k--; s = ly_cdr (s))
507         ;
508
509       if (ly_c_pair_p (s))
510         scm_set_cdr_x (s, SCM_EOL);
511     }
512   return lst;
513 }
514
515 String
516 print_scm_val (SCM val)
517 {
518   String realval = ly_scm2string (ly_write2scm (val));
519   if (realval.length () > 200)
520     realval = realval.left_string (100)
521       + "\n :\n :\n"
522       + realval.right_string (100);
523   return realval;        
524 }
525
526 bool
527 type_check_assignment (SCM sym, SCM val,  SCM type_symbol) 
528 {
529   bool ok = true;
530
531   /*
532     Always succeeds.
533
534
535     TODO: should remove #f from allowed vals?
536    */
537   if (val == SCM_EOL || val == SCM_BOOL_F)
538     return ok;
539
540   if (!ly_c_symbol_p (sym))
541 #if 0
542     return false;
543 #else
544   /*
545     This is used for autoBeamSettings.
546
547     TODO: deprecate the use of \override and \revert for
548     autoBeamSettings?
549
550     or use a symbol autoBeamSettingS?  
551    */
552   return true; 
553 #endif
554   
555   SCM type = scm_object_property (sym, type_symbol);
556
557   if (type != SCM_EOL && !ly_c_procedure_p (type))
558       {
559         warning (_f ("Can't find property type-check for `%s' (%s).",
560                      ly_symbol2string (sym).to_str0 (),
561                      ly_symbol2string (type_symbol).to_str0 ())
562                  + "  " + _ ("Perhaps you made a typing error?"));
563
564         /* Be strict when being anal :) */
565         if (internal_type_checking_global_b)
566           abort ();
567         
568         warning (_ ("Doing assignment anyway."));
569       }
570   else
571     {
572       if (val != SCM_EOL
573           && ly_c_procedure_p (type)
574           && scm_call_1 (type, val) == SCM_BOOL_F)
575         {
576           SCM errport = scm_current_error_port ();
577           ok = false;
578           SCM typefunc = ly_scheme_function ("type-name");
579           SCM type_name = scm_call_1 (typefunc, type);
580
581          
582           scm_puts (_f ("Type check for `%s' failed; value `%s' must be of type `%s'",
583                         ly_symbol2string (sym).to_str0 (),
584                         print_scm_val (val),
585                         ly_scm2string (type_name).to_str0 ()).to_str0 (),
586                     errport);
587           scm_puts ("\n", errport);                   
588         }
589     }
590   return ok;
591 }
592
593
594 /* some SCM abbrevs
595
596    zijn deze nou handig?
597    zijn ze er al in scheme, maar heten ze anders? */
598
599
600 /* Remove doubles from (sorted) list */
601 SCM
602 ly_unique (SCM list)
603 {
604   SCM unique = SCM_EOL;
605   for (SCM i = list; ly_c_pair_p (i); i = ly_cdr (i))
606     {
607       if (!ly_c_pair_p (ly_cdr (i))
608           || !ly_c_equal_p (ly_car (i), ly_cadr (i)))
609         unique = scm_cons (ly_car (i), unique);
610     }
611   return scm_reverse_x (unique, SCM_EOL);
612 }
613
614
615 static int
616 scm_default_compare (void const *a, void const *b)
617 {
618   SCM pa = *(SCM*) a;
619   SCM pb = *(SCM*) b;
620   if (pa == pb)
621     return 0;
622   return pa < pb ? -1 : 1;
623 }
624
625 /*  Modify LST in place: qsort it.  */
626 SCM
627 ly_list_qsort_uniq_x (SCM lst)
628 {
629   int len = scm_ilength (lst);
630   SCM *arr = new SCM[len];
631   int k = 0;
632   for (SCM s = lst; SCM_NNULLP (s); s = SCM_CDR (s))
633     arr[k++] = SCM_CAR (s);
634
635   assert (k == len);
636   qsort (arr, len, sizeof (SCM), &scm_default_compare);
637
638   SCM *tail = &lst;
639   for (int i = 0; i < len; i++)
640     if (!i || arr[i] != arr[i - 1])
641       {
642         SCM_SETCAR (*tail, arr[i]);
643         tail = SCM_CDRLOC (*tail);
644       }
645
646   *tail = SCM_EOL;
647   delete[] arr;
648
649   return lst; 
650 }
651
652
653 /* tail add */
654 SCM
655 ly_snoc (SCM s, SCM list)
656 {
657   return ly_append2 (list, scm_list_n (s, SCM_UNDEFINED));
658 }
659
660 /* Split list at member s, removing s.
661    Return (BEFORE . AFTER)  */
662 SCM
663 ly_split_list (SCM s, SCM list)
664 {
665   SCM before = SCM_EOL;
666   SCM after = list;
667   for (; ly_c_pair_p (after);)
668     {
669       SCM i = ly_car (after);
670       after = ly_cdr (after);
671       if (ly_c_equal_p (i, s))
672         break;
673       before = scm_cons (i, before);
674     }
675   return scm_cons ( scm_reverse_x (before, SCM_EOL),  after);
676   
677 }
678
679
680 void
681 taint (SCM *)
682 {
683   /*
684     nop.
685    */
686 }
687
688 /*
689   display stuff without using stack
690  */
691 SCM
692 display_list (SCM s)
693 {
694   SCM p = scm_current_output_port ();
695
696   scm_puts ("(", p);
697   for (; ly_c_pair_p (s); s =ly_cdr (s))
698     {
699       scm_display (ly_car (s), p);
700       scm_puts (" ", p);      
701     }
702   scm_puts (")", p);
703   return SCM_UNSPECIFIED;
704 }
705
706 Slice
707 int_list_to_slice (SCM l)
708 {
709   Slice s;
710   s.set_empty ();
711   for (; ly_c_pair_p (l); l = ly_cdr (l))
712     if (ly_c_number_p (ly_car (l)))
713       s.add_point (ly_scm2int (ly_car (l))); 
714   return s;
715 }
716
717 /* Return I-th element, or last elt L. If I < 0, then we take the first
718    element.
719    
720    PRE: length (L) > 0  */
721 SCM
722 robust_list_ref (int i, SCM l)
723 {
724   while (i-- > 0 && ly_c_pair_p (ly_cdr (l)))
725     l = ly_cdr (l);
726   return ly_car (l);
727 }
728
729 Real
730 robust_scm2double (SCM k, double x)
731 {
732   if (ly_c_number_p (k))
733     x = ly_scm2double (k);
734   return x;
735 }
736
737 Interval
738 robust_scm2interval (SCM k, Drul_array<Real> v)
739 {
740   Interval i;
741   i[LEFT]= v[LEFT];
742   i[RIGHT]= v[RIGHT];
743   if (is_number_pair (k))
744     i = ly_scm2interval (k);
745   return i;
746 }
747
748 Drul_array<Real>
749 robust_scm2drul (SCM k, Drul_array<Real> v)
750 {
751   if (is_number_pair (k))
752     v = ly_scm2interval (k);
753   return v;
754 }
755
756 Offset
757 robust_scm2offset (SCM k, Offset o)
758 {
759   if (is_number_pair (k))
760     o = ly_scm2offset (k);
761   return o;
762 }
763
764 int
765 robust_scm2int (SCM k, int o)
766 {
767   if (scm_integer_p (k) == SCM_BOOL_T)
768     o = ly_scm2int (k);
769   return o;
770 }
771
772 SCM
773 alist_to_hashq (SCM alist)
774 {
775   int i = scm_ilength (alist);
776   if (i < 0)
777     return scm_c_make_hash_table (0);
778           
779   SCM tab = scm_c_make_hash_table (i);
780   for (SCM s = alist; ly_c_pair_p (s); s = ly_cdr (s))
781     {
782       SCM pt = ly_cdar (s);
783       scm_hashq_set_x (tab, ly_caar (s), pt);
784     }
785   return tab; 
786 }
787
788 #if 1
789 /*
790   Debugging mem leaks:
791  */
792 LY_DEFINE (ly_protects, "ly:protects",
793            0, 0, 0, (),
794           "Return hash of protected objects.")
795 {
796   return scm_protects;
797 }
798 #endif
799
800
801 #if HAVE_PANGO_FC_FONT_MAP_ADD_DECODER_FIND_FUNC
802
803 #include "pangofc-afm-decoder.hh"
804
805 LY_DEFINE (ly_pango_add_afm_decoder, "ly:pango-add-afm-decoder",
806            1, 0, 0, (SCM font_family),
807            "Add pango afm decoder for FONT-FAMILY.")
808 {
809   SCM_ASSERT_TYPE (scm_is_string (font_family), font_family, SCM_ARG1,
810                    __FUNCTION__, "font_family");
811   pango_fc_afm_add_decoder (ly_scm2newstr (font_family, 0));
812   return SCM_UNSPECIFIED;
813 }
814
815 #endif
816
817 LY_DEFINE (ly_gettext, "ly:gettext",
818            1, 0, 0, (SCM string),
819            "Gettext wrapper.")
820 {
821   SCM_ASSERT_TYPE (scm_is_string (string), string, SCM_ARG1,
822                    __FUNCTION__, "string");
823   return scm_makfrom0str (gettext (scm_i_string_chars (string)));
824 }