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