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