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