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