]> git.donarmstrong.com Git - lilypond.git/blob - lily/lily-guile.cc
*** empty log message ***
[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_dir_p, "ly:dir?",
185            1, 0, 0, (SCM s),
186           "type predicate. A direction is @code{-1}, @code{0} or "
187            "@code{1}, where @code{-1} represents "
188           "left or down and @code{1} represents right or up.")
189 {
190   if (ly_c_number_p (s))
191     {
192       int i = ly_scm2int (s);
193       return (i>= -1 && i <= 1)  ? SCM_BOOL_T : SCM_BOOL_F; 
194     }
195   return SCM_BOOL_F;
196 }
197
198 bool
199 is_number_pair (SCM p)
200 {
201   return ly_c_pair_p (p)
202     && ly_c_number_p (ly_car (p)) && ly_c_number_p (ly_cdr (p));
203 }
204
205 typedef void (*Void_fptr) ();
206 Array<Void_fptr> *scm_init_funcs_;
207
208 void add_scm_init_func (void (*f) ())
209 {
210   if (!scm_init_funcs_)
211     scm_init_funcs_ = new Array<Void_fptr>;
212
213   scm_init_funcs_->push (f);
214 }
215
216 void
217 ly_init_ly_module (void *)
218 {
219   for (int i=scm_init_funcs_->size () ; i--;)
220     (scm_init_funcs_->elem (i)) ();
221
222   if (verbose_global_b)
223     progress_indication ("\n");
224   
225   scm_primitive_load_path (scm_makfrom0str ("lily.scm"));
226 }
227
228 SCM global_lily_module;
229
230 void
231 ly_c_init_guile ()
232 {
233   global_lily_module = scm_c_define_module ("lily", ly_init_ly_module, 0);
234   scm_c_use_module ("lily");
235 }
236
237 unsigned int
238 ly_scm_hash (SCM s)
239 {
240   return scm_ihashv (s, ~1u);
241 }
242
243 bool
244 is_direction (SCM s)
245 {
246   if (ly_c_number_p (s))
247     {
248       int i = ly_scm2int (s);
249       return i>= -1 && i <= 1; 
250     }
251   return false;
252 }
253
254 bool
255 is_axis (SCM s)
256 {
257   if (ly_c_number_p (s))
258     {
259       int i = ly_scm2int (s);
260       return i== 0 || i == 1;
261     }
262   return false;
263 }
264
265 Direction
266 to_dir (SCM s)
267 {
268   return scm_is_integer (s) ? (Direction) ly_scm2int (s) : CENTER;
269 }
270
271 Interval
272 ly_scm2interval (SCM p)
273 {
274   return Interval (ly_scm2double (ly_car (p)), ly_scm2double (ly_cdr (p)));
275 }
276
277 Drul_array<Real>
278 ly_scm2realdrul (SCM p)
279 {
280   return Drul_array<Real> (ly_scm2double (ly_car (p)),
281                            ly_scm2double (ly_cdr (p)));
282 }
283
284 SCM
285 ly_interval2scm (Drul_array<Real> i)
286 {
287   return scm_cons (scm_make_real (i[LEFT]), scm_make_real (i[RIGHT]));
288 }
289
290 bool
291 to_boolean (SCM s)
292 {
293   return ly_c_boolean_p (s) && ly_scm2bool (s);
294 }
295
296 /* Appendable list L: the cdr contains the list, the car the last cons
297    in the list.  */
298 SCM
299 appendable_list ()
300 {
301   SCM s = scm_cons (SCM_EOL, SCM_EOL);
302   scm_set_car_x (s, s);
303   
304   return s;
305 }
306
307 void
308 appendable_list_append (SCM l, SCM elt)
309 {
310   SCM newcons = scm_cons (elt, SCM_EOL);
311   
312   scm_set_cdr_x (ly_car (l), newcons);      
313   scm_set_car_x (l, newcons);
314 }
315
316 SCM
317 ly_offset2scm (Offset o)
318 {
319   return scm_cons (scm_make_real (o[X_AXIS]), scm_make_real (o[Y_AXIS]));
320 }
321
322 Offset
323 ly_scm2offset (SCM s)
324 {
325   return Offset (ly_scm2double (ly_car (s)),
326                  ly_scm2double (ly_cdr (s)));
327 }
328
329 LY_DEFINE (ly_number2string, "ly:number->string",
330            1, 0, 0, (SCM s),
331            "Convert @var{num} to a string without generating many decimals.")
332 {
333   SCM_ASSERT_TYPE (ly_c_number_p (s), s, SCM_ARG1, __FUNCTION__, "number");
334
335   char str[400];                        // ugh.
336
337   if (scm_exact_p (s) == SCM_BOOL_F)
338     {
339       Real r (ly_scm2double (s));
340
341       if (my_isinf (r) || my_isnan (r))
342         {
343           programming_error ("Infinity or NaN encountered while converting Real number; setting to zero.");
344           r = 0.0;
345         }
346
347       sprintf (str, "%08.4f", r);
348     }
349   else
350     sprintf (str, "%d", ly_scm2int (s));
351
352   return scm_makfrom0str (str);
353 }
354
355
356
357 LY_DEFINE (ly_version,  "ly:version", 0, 0, 0, (),
358           "Return the current lilypond version as a list, e.g. @code{(1 3 127 uu1)}. ")
359 {
360   char const* vs = "\'(" MAJOR_VERSION " " MINOR_VERSION " "  PATCH_LEVEL " " MY_PATCH_LEVEL ")" ;
361   
362   return scm_c_eval_string ((char*)vs);
363 }
364
365 LY_DEFINE (ly_unit,  "ly:unit", 0, 0, 0, (),
366           "Return the unit used for lengths as a string.")
367 {
368   return scm_makfrom0str (INTERNAL_UNIT);
369 }
370
371
372
373 LY_DEFINE (ly_dimension_p,  "ly:dimension?", 1, 0, 0, (SCM d),
374           "Return @var{d} is a number. Used to distinguish length "
375           "variables from normal numbers.")
376 {
377   return scm_number_p (d);
378 }
379
380 SCM
381 ly_deep_copy (SCM src)
382 {
383   if (ly_c_pair_p (src))
384     return scm_cons (ly_deep_copy (ly_car (src)), ly_deep_copy (ly_cdr (src)));
385   else if (ly_c_vector_p (src))
386     {
387       int len = SCM_VECTOR_LENGTH (src);
388       SCM nv = scm_c_make_vector (len, SCM_UNDEFINED);
389       for (int i  =0 ; i < len ; i++)
390         {
391           SCM si = scm_int2num (i);
392           scm_vector_set_x (nv, si, ly_deep_copy (scm_vector_ref (src, si))); 
393         }
394     }
395   return src;
396 }
397
398
399
400
401 SCM
402 ly_assoc_chain (SCM key, SCM achain)
403 {
404   if (ly_c_pair_p (achain))
405     {
406       SCM handle = scm_assoc (key, ly_car (achain));
407       if (ly_c_pair_p (handle))
408         return handle;
409       else
410         return ly_assoc_chain (key, ly_cdr (achain));
411     }
412   else
413     return SCM_BOOL_F;
414 }
415
416 /* looks the key up in the cdrs of the alist-keys
417    - ignoring the car and ignoring non-pair keys.
418    Returns first match found, i.e.
419
420    alist = ((1 . 10)
421                    ((1 . 2) . 11)
422                    ((2 . 1) . 12)
423                    ((3 . 0) . 13)
424                    ((4 . 1) . 14) )
425
426 I would like (ly_assoc_cdr 1) to return 12 - because it's the first
427 element with the cdr of the key = 1.  In other words (alloc_cdr key)
428 corresponds to call
429
430 (alloc (anything . key))
431
432
433
434 */
435 SCM
436 ly_assoc_cdr (SCM key, SCM alist)
437 {
438   if (ly_c_pair_p (alist))
439     {
440       SCM trykey = ly_caar (alist);
441       if (ly_c_pair_p (trykey) && to_boolean (scm_equal_p (key, ly_cdr (trykey))))
442         return ly_car (alist);
443       else
444         return ly_assoc_cdr (key, ly_cdr (alist));
445     }
446   return SCM_BOOL_F;
447 }
448
449 /* LST has the form "sym1 sym2 sym3\nsym4\nsym5"
450    i.e. \n and ' ' can be used interchangeably as separators.  */
451 SCM
452 parse_symbol_list (char const *lst)
453 {
454   char *s = strdup (lst);
455   char *orig = s;
456   SCM create_list = SCM_EOL;
457
458   char * e = s + strlen (s) - 1;
459   while (e >= s && isspace (*e))
460     *e-- = 0;
461
462   for (char * p = s; *p; p++)
463     if (*p == '\n')
464       *p = ' ';
465   
466   if (!s[0])
467     s = 0;
468   
469   while (s)
470     {
471       char *next = strchr (s, ' ');
472       if (next)
473         *next++ = 0;
474
475       create_list = scm_cons (ly_symbol2scm (s), create_list);
476       s = next;
477     }
478
479   free (orig);
480   return create_list;
481 }
482
483 SCM
484 ly_truncate_list (int k, SCM lst)
485 {
486   if (k == 0)
487     lst = SCM_EOL;
488   else
489     {
490       SCM s = lst;
491       k--;
492       for (; ly_c_pair_p (s) && k--; s = ly_cdr (s))
493         ;
494
495       if (ly_c_pair_p (s))
496         scm_set_cdr_x (s, SCM_EOL);
497     }
498   return lst;
499 }
500
501 String
502 print_scm_val (SCM val)
503 {
504   String realval = ly_scm2string (ly_write2scm (val));
505   if (realval.length () > 200)
506     realval = realval.left_string (100)
507       + "\n :\n :\n"
508       + realval.right_string (100);
509   return realval;        
510 }
511
512 bool
513 type_check_assignment (SCM sym, SCM val,  SCM type_symbol) 
514 {
515   bool ok = true;
516
517   /*
518     Always succeeds.
519
520
521     TODO: should remove #f from allowed vals?
522    */
523   if (val == SCM_EOL || val == SCM_BOOL_F)
524     return ok;
525
526   if (!ly_c_symbol_p (sym))
527 #if 0
528     return false;
529 #else
530   /*
531     This is used for autoBeamSettings.
532
533     TODO: deprecate the use of \override and \revert for
534     autoBeamSettings?
535
536     or use a symbol autoBeamSettingS?  
537    */
538   return true; 
539 #endif
540   
541   SCM type = scm_object_property (sym, type_symbol);
542
543   if (type != SCM_EOL && !ly_c_procedure_p (type))
544       {
545         warning (_f ("Can't find property type-check for `%s' (%s).",
546                      ly_symbol2string (sym).to_str0 (),
547                      ly_symbol2string (type_symbol).to_str0 ())
548                  + "  " + _ ("Perhaps you made a typing error?"));
549
550         /* Be strict when being anal :) */
551         if (internal_type_checking_global_b)
552           abort ();
553         
554         warning (_ ("Doing assignment anyway."));
555       }
556   else
557     {
558       if (val != SCM_EOL
559           && ly_c_procedure_p (type)
560           && scm_call_1 (type, val) == SCM_BOOL_F)
561         {
562           SCM errport = scm_current_error_port ();
563           ok = false;
564           SCM typefunc = ly_scheme_function ("type-name");
565           SCM type_name = scm_call_1 (typefunc, type);
566
567          
568           scm_puts (_f ("Type check for `%s' failed; value `%s' must be of type `%s'",
569                         ly_symbol2string (sym).to_str0 (),
570                         print_scm_val (val),
571                         ly_scm2string (type_name).to_str0 ()).to_str0 (),
572                     errport);
573           scm_puts ("\n", errport);                   
574         }
575     }
576   return ok;
577 }
578
579
580 /* some SCM abbrevs
581
582    zijn deze nou handig?
583    zijn ze er al in scheme, maar heten ze anders? */
584
585
586 /* Remove doubles from (sorted) list */
587 SCM
588 ly_unique (SCM list)
589 {
590   SCM unique = SCM_EOL;
591   for (SCM i = list; ly_c_pair_p (i); i = ly_cdr (i))
592     {
593       if (!ly_c_pair_p (ly_cdr (i))
594           || !ly_c_equal_p (ly_car (i), ly_cadr (i)))
595         unique = scm_cons (ly_car (i), unique);
596     }
597   return scm_reverse_x (unique, SCM_EOL);
598 }
599
600
601 static int
602 scm_default_compare (void const *a, void const *b)
603 {
604   SCM pa = *(SCM*) a;
605   SCM pb = *(SCM*) b;
606   if (pa == pb)
607     return 0;
608   return pa < pb ? -1 : 1;
609 }
610
611 /*  Modify LST in place: qsort it.  */
612 SCM
613 ly_list_qsort_uniq_x (SCM lst)
614 {
615   int len = scm_ilength (lst);
616   SCM *arr = new SCM[len];
617   int k = 0;
618   for (SCM s = lst; SCM_NNULLP (s); s = SCM_CDR (s))
619     arr[k++] = SCM_CAR (s);
620
621   assert (k == len);
622   qsort (arr, len, sizeof (SCM), &scm_default_compare);
623
624   SCM *tail = &lst;
625   for (int i = 0; i < len; i++)
626     if (!i || arr[i] != arr[i - 1])
627       {
628         SCM_SETCAR (*tail, arr[i]);
629         tail = SCM_CDRLOC (*tail);
630       }
631
632   *tail = SCM_EOL;
633   delete[] arr;
634
635   return lst; 
636 }
637
638
639 /* tail add */
640 SCM
641 ly_snoc (SCM s, SCM list)
642 {
643   return ly_append2 (list, scm_list_n (s, SCM_UNDEFINED));
644 }
645
646 /* Split list at member s, removing s.
647    Return (BEFORE . AFTER)  */
648 SCM
649 ly_split_list (SCM s, SCM list)
650 {
651   SCM before = SCM_EOL;
652   SCM after = list;
653   for (; ly_c_pair_p (after);)
654     {
655       SCM i = ly_car (after);
656       after = ly_cdr (after);
657       if (ly_c_equal_p (i, s))
658         break;
659       before = scm_cons (i, before);
660     }
661   return scm_cons ( scm_reverse_x (before, SCM_EOL),  after);
662   
663 }
664
665
666 void
667 taint (SCM *)
668 {
669   /*
670     nop.
671    */
672 }
673
674 /*
675   display stuff without using stack
676  */
677 SCM
678 display_list (SCM s)
679 {
680   SCM p = scm_current_output_port ();
681
682   scm_puts ("(", p);
683   for (; ly_c_pair_p (s); s =ly_cdr (s))
684     {
685       scm_display (ly_car (s), p);
686       scm_puts (" ", p);      
687     }
688   scm_puts (")", p);
689   return SCM_UNSPECIFIED;
690 }
691
692 Slice
693 int_list_to_slice (SCM l)
694 {
695   Slice s;
696   s.set_empty ();
697   for (; ly_c_pair_p (l); l = ly_cdr (l))
698     if (ly_c_number_p (ly_car (l)))
699       s.add_point (ly_scm2int (ly_car (l))); 
700   return s;
701 }
702
703 /* Return I-th element, or last elt L. If I < 0, then we take the first
704    element.
705    
706    PRE: length (L) > 0  */
707 SCM
708 robust_list_ref (int i, SCM l)
709 {
710   while (i-- > 0 && ly_c_pair_p (ly_cdr (l)))
711     l = ly_cdr (l);
712   return ly_car (l);
713 }
714
715 Real
716 robust_scm2double (SCM k, double x)
717 {
718   if (ly_c_number_p (k))
719     x = ly_scm2double (k);
720   return x;
721 }
722
723 Interval
724 robust_scm2interval (SCM k, Drul_array<Real> v)
725 {
726   Interval i;
727   i[LEFT]= v[LEFT];
728   i[RIGHT]= v[RIGHT];
729   if (is_number_pair (k))
730     i = ly_scm2interval (k);
731   return i;
732 }
733
734 Drul_array<Real>
735 robust_scm2drul (SCM k, Drul_array<Real> v)
736 {
737   if (is_number_pair (k))
738     v = ly_scm2interval (k);
739   return v;
740 }
741
742 Offset
743 robust_scm2offset (SCM k, Offset o)
744 {
745   if (is_number_pair (k))
746     o = ly_scm2offset (k);
747   return o;
748 }
749
750 int
751 robust_scm2int (SCM k, int o)
752 {
753   if (scm_integer_p (k) == SCM_BOOL_T)
754     o = ly_scm2int (k);
755   return o;
756 }
757
758 SCM
759 alist_to_hashq (SCM alist)
760 {
761   int i = scm_ilength (alist);
762   if (i < 0)
763     return scm_make_vector (scm_int2num (0), SCM_EOL);
764           
765   SCM tab = scm_make_vector (scm_int2num (i), SCM_EOL);
766   for (SCM s = alist; ly_c_pair_p (s); s = ly_cdr (s))
767     {
768       SCM pt = ly_cdar (s);
769       scm_hashq_set_x (tab, ly_caar (s), pt);
770     }
771   return tab; 
772 }
773
774 #if 1
775 /*
776   Debugging mem leaks:
777  */
778 LY_DEFINE (ly_protects, "ly:protects",
779            0, 0, 0, (),
780           "Return hash of protected objects.")
781 {
782   return scm_protects;
783 }
784 #endif
785
786
787 #if HAVE_PANGO_FC_FONT_MAP_ADD_DECODER_FIND_FUNC
788
789 #include "pangofc-afm-decoder.hh"
790
791 LY_DEFINE (ly_pango_add_afm_decoder, "ly:pango-add-afm-decoder",
792            1, 0, 0, (SCM font_family),
793            "Add pango afm decoder for FONT-FAMILY.")
794 {
795   SCM_ASSERT_TYPE (ly_c_string_p (font_family), font_family, SCM_ARG1, __FUNCTION__, "font_family");
796   pango_fc_afm_add_decoder (ly_scm2newstr (font_family, 0));
797   return SCM_UNSPECIFIED;
798 }
799
800 #endif