]> git.donarmstrong.com Git - lilypond.git/blob - scm/lily.scm
Merge branch 'master' of git+ssh://jneem@git.sv.gnu.org/srv/git/lilypond
[lilypond.git] / scm / lily.scm
1 ;;;; lily.scm -- toplevel Scheme stuff
2 ;;;;
3 ;;;;  source file of the GNU LilyPond music typesetter
4 ;;;; 
5 ;;;; (c) 1998--2006 Jan Nieuwenhuizen <janneke@gnu.org>
6 ;;;; Han-Wen Nienhuys <hanwen@xs4all.nl>
7
8 ;; Internationalisation: (_i "to be translated") gets an entry in the
9 ;; POT file (gettext ) must be invoked explicitely to do the actual
10 ;; "translation".
11 ;;(define-macro (_i x) x)
12 ;;(define-macro-public _i (x) x)
13 ;;(define-public-macro _i (x) x)
14 ;; Abbrv-PWR!
15 (defmacro-public _i (x) x)
16
17 (read-enable 'positions)
18 (debug-enable 'debug)
19
20
21 (define (define-scheme-options)
22   (for-each (lambda (x)
23               (ly:add-option (car x) (cadr x) (caddr x)))
24           
25             `(
26
27               ;; NAMING: either
28
29               ;; - [subject-]object-object-verb +"ing"
30               ;; - [subject-]-verb-object-object
31
32               (anti-alias-factor 1 "render at higher resolution and scale down result\nto prevent jaggies in PNG")
33               (check-internal-types #f "check every property assignment for types")
34               (clip-systems #f "Generate cut-out snippets of a score")
35               (debug-gc #f "dump memory debugging statistics")
36               (debug-gc-assert-parsed-dead #f "for memory debugging:
37 ensure that all refs to parsed objects are dead.  This is an internal option, and is switched on automatically for -ddebug-gc.") 
38               (debug-lexer #f "debug the flex lexer")
39               (debug-midi #f "generate human readable MIDI")
40               (debug-parser #f "debug the bison parser")
41               (debug-skylines #f "debug skylines")
42               (delete-intermediate-files #f
43                                          "delete unusable PostScript files")
44               (dump-profile #f "dump timing information for each file")
45               (dump-signatures #f "dump output signatures of each system.  Used for regression testing.")
46               
47               (eps-box-padding #f "Pad EPS bounding box left edge.  Guarantee alignment between systems in LaTeX.")
48               (gs-load-fonts #f
49                             "load fonts via Ghostscript.")
50               (gui #f "running from gui; redirect stderr to log file")
51
52               (include-book-title-preview #t "include book-titles in preview images.")
53               (include-eps-fonts #t "Include fonts in separate-system EPS files.")
54               (job-count #f "Process in parallel") 
55               (log-file #f "redirect output to log FILE.log")
56
57               (old-relative #f
58                             "relative for simultaneous music works
59 similar to chord syntax")
60               (point-and-click #t "use point & click")
61               (paper-size "a4" "the default paper size")
62               (pixmap-format "png16m" "GS format to use for pixel images")
63               (protected-scheme-parsing #t "continue when finding errors in inline
64 scheme are caught in the parser. If off, halt 
65 on errors, and print a stack trace.")
66               (profile-property-accesses #f "keep statistics of get_property() calls.")
67               
68               (resolution 101 "resolution for generating PNG bitmaps")
69               (read-file-list #f "Read files to be processed from command line arguments")
70
71               (safe #f "Run safely")
72               (strict-infinity-checking #f "If yes, crash on encountering Inf/NaN.")
73               (separate-log-files #f "Output to FILE.log per file.")
74               (ttf-verbosity 0
75                              "how much verbosity for TTF font embedding?")
76               (show-available-fonts #f
77                                     "List font names available.")
78               (verbose ,(ly:command-line-verbose?) "value for the --verbose flag")
79               ))
80
81   (map
82    (lambda (x)
83      (ly:set-option (car x) (cdr x))) 
84    (eval-string (ly:command-line-options))))
85
86
87 ;; need to do this in the beginning. Other parts of the
88 ;; Scheme init depend on these options.
89 ;;
90 (define-scheme-options)
91
92
93
94 (debug-set! stack 0)
95
96 (if (defined? 'set-debug-cell-accesses!)
97     (set-debug-cell-accesses! #f))
98
99                                         ;(set-debug-cell-accesses! 1000)
100
101 (use-modules (ice-9 regex)
102              (ice-9 safe)
103              (ice-9 optargs)
104              (oop goops)
105              (srfi srfi-1)
106              (srfi srfi-13)
107              (srfi srfi-14)
108              (scm clip-region)
109              )
110
111 ;; my display
112 (define-public (myd k v) (display k) (display ": ") (display v) (display ", ")
113   v)
114
115 (define-public (print . args)
116   (apply format (cons (current-output-port) args)))
117
118
119 ;;; General settings
120 ;;; debugging evaluator is slower.  This should
121 ;;; have a more sensible default.
122
123 (if (ly:get-option 'verbose)
124     (begin
125       (ly:set-option 'protected-scheme-parsing #f)
126       (debug-enable 'debug)
127       (debug-enable 'backtrace)
128       (read-enable 'positions)))
129
130 (define-public tex-backend?
131   (member (ly:output-backend) '("texstr" "tex")))
132
133 (define-public parser #f)
134
135 (define-public (lilypond-version)
136   (string-join
137    (map (lambda (x) (if (symbol? x)
138                         (symbol->string x)
139                         (number->string x)))
140         (ly:version))
141    "."))
142
143
144 ;; TeX C++ code actually hooks into TEX_STRING_HASHLIMIT 
145 (define-public TEX_STRING_HASHLIMIT 10000000)
146
147
148
149 ;; gettext wrapper for guile < 1.7.2
150 (if (defined? 'gettext)
151     (define-public _ gettext)
152     (define-public _ ly:gettext))
153
154 (define-public (ly:load x)
155   (let* ((file-name (%search-load-path x)))
156     (if (ly:get-option 'verbose)
157         (ly:progress "[~A" file-name))
158     (if (not file-name)
159         (ly:error (_ "cannot find: ~A") x))
160     (primitive-load file-name)
161     (if (ly:get-option 'verbose)
162         (ly:progress "]"))))
163
164 ;; Cygwin
165 ;; #(CYGWIN_NT-5.1 Hostname 1.5.12(0.116/4/2) 2004-11-10 08:34 i686)
166 ;;
167 ;; Debian
168 ;; #(Linux hostname 2.4.27-1-686 #1 Fri Sep 3 06:28:00 UTC 2004 i686)
169 ;;
170 ;; Mingw
171 ;; #(Windows XP HOSTNAME build 2600 5.01 Service Pack 1 i686)
172 ;;
173
174 ;; ugh, code dup.
175 (define-public PLATFORM
176   (string->symbol
177    (string-downcase
178     (car (string-tokenize (vector-ref (uname) 0) char-set:letter)))))
179
180 (define-public DOS
181   (let ((platform (string-tokenize
182                    (vector-ref (uname) 0) char-set:letter+digit)))
183     (if (null? (cdr platform)) #f
184         (member (string-downcase (cadr platform)) '("95" "98" "me")))))
185
186 (case PLATFORM
187   ((windows)
188    (define native-getcwd getcwd)
189    (define (slashify x)
190      (if (string-index x #\\)
191          x
192          (string-regexp-substitute
193           "//*" "/"
194           (string-regexp-substitute "\\\\" "/" x))))
195    ;; FIXME: this prints a warning.
196    (define-public (ly-getcwd)
197      (slashify (native-getcwd))))
198   (else (define-public ly-getcwd getcwd)))
199
200 (define-public (is-absolute? file-name)
201   (let ((file-name-length (string-length file-name)))
202     (if (= file-name-length 0)
203         #f
204         (or (eq? (string-ref file-name 0) #\/)
205             (and (eq? PLATFORM 'windows)
206                  (> file-name-length 2)
207                  (eq? (string-ref file-name 1) #\:)
208                  (eq? (string-ref file-name 2) #\/))))))
209
210 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
211
212 (define (type-check-list location signature arguments)
213   "Typecheck a list of arguments against a list of type
214 predicates. Print a message at LOCATION if any predicate failed."
215
216   (define (recursion-helper signature arguments count) 
217     (define (helper pred? arg count) 
218       (if (not (pred? arg))
219
220           (begin
221             (ly:input-message
222              location
223              (format
224               #f (_ "wrong type for argument ~a.  Expecting ~a, found ~s")
225               count (type-name pred?) arg))
226             #f)
227           #t))
228
229     (if (null? signature)
230         #t
231         (and (helper (car signature) (car arguments) count)
232              (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
233
234   (recursion-helper signature arguments 1))
235
236 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
237 ;;  output
238
239
240 ;;(define-public (output-framework) (write "hello\n"))
241
242 (define output-tex-module
243   (make-module 1021 (list (resolve-interface '(scm output-tex)))))
244 (define output-ps-module
245   (make-module 1021 (list (resolve-interface '(scm output-ps)))))
246
247 (define-public (ps-output-expression expr port)
248   (display (eval expr output-ps-module) port))
249
250 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
251 ;; Safe definitions utility
252 (define safe-objects (list))
253
254 (define-macro (define-safe-public arglist . body)
255   "Define a variable, export it, and mark it as safe, ie usable in LilyPond safe mode.
256 The syntax is the same as `define*-public'."
257   (define (get-symbol arg)
258     (if (pair? arg)
259         (get-symbol (car arg))
260         arg))
261   (let ((safe-symbol (get-symbol arglist)))
262     `(begin
263        (define*-public ,arglist
264          ,@body)
265        (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
266                                 safe-objects))
267        ,safe-symbol)))
268
269 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
270 ;; init pitch system
271
272 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
273
274
275
276 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
277 ;; other files.
278
279
280 (define
281   init-scheme-files
282   '("lily-library.scm"
283             "file-cache.scm"
284             "define-event-classes.scm"
285             "define-music-types.scm"
286             "output-lib.scm"
287             "c++.scm"
288             "chord-ignatzek-names.scm"
289             "chord-entry.scm"
290             "chord-generic-names.scm"
291             "stencil.scm"
292             "markup.scm"
293             "music-functions.scm"
294             "part-combiner.scm"
295             "autochange.scm"
296             "define-music-properties.scm"
297             "auto-beam.scm"
298             "chord-name.scm"
299
300             "parser-ly-from-scheme.scm"
301             "ly-syntax-constructors.scm"
302             
303             "define-context-properties.scm"
304             "translation-functions.scm"
305             "script.scm"
306             "midi.scm"
307             "layout-beam.scm"
308             "parser-clef.scm"
309             "layout-slur.scm"
310             "font.scm"
311             "encoding.scm"
312             
313             "fret-diagrams.scm"
314             "define-markup-commands.scm"
315             "define-grob-properties.scm"
316             "define-grobs.scm"
317             "define-grob-interfaces.scm"
318             "define-stencil-commands.scm"
319             "titling.scm"
320             
321             "paper.scm"
322             "backend-library.scm"
323             "x11-color.scm"
324
325             ;; must be after everything has been defined
326             "safe-lily.scm"))
327
328
329
330
331 (for-each ly:load init-scheme-files)
332
333
334 (set! type-p-name-alist
335       `(
336         (,boolean-or-symbol? . "boolean or symbol")
337         (,boolean? . "boolean")
338         (,char? . "char")
339         (,grob-list? . "list of grobs")
340         (,hash-table? . "hash table")
341         (,input-port? . "input port")
342         (,integer? . "integer")
343         (,list? . "list")
344         (,ly:context? . "context")
345         (,ly:dimension? . "dimension, in staff space")
346         (,ly:dir? . "direction")
347         (,ly:duration? . "duration")
348         (,ly:grob? . "layout object")
349         (,ly:input-location? . "input location")
350         (,ly:moment? . "moment")
351         (,ly:music? . "music")
352         (,ly:pitch? . "pitch")
353         (,ly:translator? . "translator")
354         (,ly:font-metric? . "font metric")
355         (,ly:simple-closure? . "simple closure")
356         (,markup-list? . "list of markups")
357         (,markup? . "markup")
358         (,ly:music-list? . "list of music")
359         (,number-or-grob? . "number or grob")
360         (,number-or-string? . "number or string")
361         (,number-pair? . "pair of numbers")
362         (,number? . "number")
363         (,output-port? . "output port")   
364         (,pair? . "pair")
365         (,procedure? . "procedure")
366         (,rhythmic-location? . "rhythmic location")
367         (,scheme? . "any type")
368         (,string? . "string")
369         (,symbol? . "symbol")
370         (,vector? . "vector")))
371
372 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
373 ;; timing
374
375 (define (profile-measurements)
376   (let* ((t (times))
377          (stats (gc-stats)))
378     
379     (list
380      (- (+ (tms:cutime t)
381            (tms:utime t))
382         (ly:assoc-get 'gc-time-taken stats))
383      
384      (ly:assoc-get 'total-cells-allocated  stats 0)
385      )))
386
387 (define (dump-profile base last this)
388   (let*
389       ((outname (format "~a.profile" (basename base ".ly")))
390        (diff (map (lambda (y) (apply - y)) (zip this last))))
391     
392     (ly:progress "\nWriting timing to ~a..." outname)
393     (format (open-file outname "w")
394             "time: ~a\ncells: ~a\n"
395             (car diff)
396             (cadr diff)
397             )))
398
399
400 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
401 ;; debug mem leaks
402
403 (define gc-dumping #f)
404 (define gc-protect-stat-count 0)
405 (define-public (dump-gc-protects)
406   (set! gc-protect-stat-count (1+ gc-protect-stat-count))
407   (let* ((protects (sort
408                     (hash-table->alist (ly:protects))
409                     (lambda (a b)
410                       (< (object-address (car a))
411                          (object-address (car b))))))
412
413          (out-file-name (string-append
414                          "gcstat-" (number->string gc-protect-stat-count)
415                          ".scm"))
416          (outfile    (open-file  out-file-name  "w")))
417
418     (set! gc-dumping #t)
419     (display (format "Dumping GC statistics ~a...\n" out-file-name))
420     (display
421      (map (lambda (y)
422             (let ((x (car y))
423                   (c (cdr y)))
424               (display 
425                (format "~a (~a) = ~a\n" (object-address x) c x)
426                outfile)))
427           (filter
428            (lambda (x)
429              (not (symbol? (car x))))
430            protects))
431      outfile)
432
433     (format outfile "\nprotected symbols: ~a\n"
434             (length (filter symbol?  (map car protects))))
435     
436              
437
438     ;; (display (ly:smob-protects))
439     (newline outfile)
440     (if (defined? 'gc-live-object-stats)
441         (let* ((stats #f))
442           (display "Live object statistics: GC'ing\n")
443           (ly:reset-all-fonts)
444           (gc)
445           (gc)
446           (display "Asserting dead objects\n")
447           (ly:set-option 'debug-gc-assert-parsed-dead #t)
448           (gc)
449           (ly:set-option 'debug-gc-assert-parsed-dead #f)
450
451           (set! stats (gc-live-object-stats))
452           (display "Dumping live object statistics.\n")
453           
454           (for-each
455            (lambda (x)
456              (format outfile "~a: ~a\n" (car x) (cdr x)))
457            (sort (gc-live-object-stats)
458                  (lambda (x y)
459                    (string<? (car x) (car y)))))))
460
461
462     (newline outfile)
463     (let*
464         ((stats (gc-stats)))
465       
466       (for-each
467        (lambda (sym)
468          (display
469           (format "~a ~a ~a\n"
470                   gc-protect-stat-count
471                   sym
472                   (let ((sym-stat (assoc sym stats)))
473                     (if sym-stat 
474                         (cdr sym-stat)
475                         "?")))
476           outfile))
477        '(protected-objects bytes-malloced cell-heap-size
478                            
479                            )))
480
481     (set! gc-dumping #f)
482     
483     ))
484
485 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
486
487
488 (define (multi-fork count)
489   (define (helper count acc)
490     (if (> count 0)
491       (let*
492           ((pid  (primitive-fork)))
493         (if (= pid 0)
494             (1- count)
495             (helper (1- count) (cons pid acc))))
496       acc))
497   (helper count '()))
498
499
500 (define-public (lilypond-main files)
501   "Entry point for LilyPond."
502
503   (define (no-files-handler)
504     (ly:usage)
505     (exit 2))
506
507   (eval-string (ly:command-line-code))
508   
509   (if (ly:get-option 'gui)
510       (gui-main files))
511
512   (if (null? files)
513       (no-files-handler))
514
515   (if (ly:get-option 'read-file-list)
516       (set! files
517             (filter (lambda (s)
518                       (> (string-length s) 0))
519                     (apply append
520                            (map (lambda (f) (string-split (ly:gulp-file f) #\nl))
521                                 files)))
522             ))
523   
524   (if (and (number? (ly:get-option 'job-count))
525            (>= (length files) (ly:get-option 'job-count)))
526       
527       (let*
528           ((count (ly:get-option 'job-count))
529            (split-todo (split-list files count)) 
530            (joblist (multi-fork count))
531            (errors '()))
532
533         (if (not (string-or-symbol? (ly:get-option 'log-file)))
534             (ly:set-option 'log-file "lilypond-multi-run"))
535         
536         (if (number? joblist)
537             (begin
538               (ly:set-option 'log-file (format "~a-~a"
539                                                (ly:get-option 'log-file) joblist))
540               (set! files (vector-ref split-todo joblist)))
541
542             (begin
543               (ly:progress "\nForking into jobs:  ~a\n" joblist)
544               (for-each
545                (lambda (pid)
546                  (let* ((stat (cdr (waitpid pid))))
547                    
548                    (if (not (= stat 0))
549                        (set! errors (acons (list-element-index joblist pid) stat errors)))))
550                joblist)
551
552               (for-each
553                (lambda (x)
554                  (let* ((job (car x))
555                         (state (cdr x))
556                         (logfile  (format "~a-~a.log"
557                                           (ly:get-option 'log-file) job))
558                         (log (ly:gulp-file logfile))
559                         (len (string-length log))
560                         (tail (substring  log (max 0 (- len 1024)))))
561
562                    (if (status:term-sig state)
563                        (ly:message "\n\n~a\n"
564                                    (format (_ "job ~a terminated with signal: ~a")
565                                            job
566                                            (status:term-sig state)))
567                        (ly:message (_ "logfile ~a (exit ~a):\n~a") logfile (status:exit-val state) tail))))
568
569                errors)
570
571               (if (pair? errors)
572                   (ly:error "Children ~a exited with errors." (map car errors)))
573
574               ;; must overwrite individual entries
575               (if (ly:get-option 'dump-profile)
576                   (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
577
578             (exit (if (null? errors) 0 1))))))
579               
580            
581   (if (string-or-symbol? (ly:get-option 'log-file))
582       (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
583
584   
585   (let ((failed (lilypond-all files)))
586     (if (pair? failed)
587         (begin
588           (ly:error (_ "failed files: ~S") (string-join failed))
589           (exit 1))
590         (begin
591           ;; HACK: be sure to exit with single newline
592           (ly:message "")
593           (exit 0)))))
594
595 (define-public (lilypond-all files)
596   
597
598   (if (ly:get-option 'show-available-fonts)
599       (begin
600         (ly:font-config-display-fonts)
601         (exit 0)
602         ))
603   
604   (let* ((failed '())
605          (separate-logs (ly:get-option 'separate-log-files))
606          (do-measurements (ly:get-option 'dump-profile))
607          (handler (lambda (key failed-file)
608                     (set! failed (append (list failed-file) failed)))))
609
610     (gc)
611     (for-each
612      (lambda (x)
613        (let*
614            ((start-measurements (if do-measurements
615                                     (profile-measurements)
616                                     #f))
617             (base (basename x ".ly"))
618             (all-settings (ly:all-options)))
619
620          (if separate-logs
621              (ly:stderr-redirect (format "~a.log" base) "w"))
622        
623          (lilypond-file handler x)
624          (if start-measurements
625              (dump-profile x start-measurements (profile-measurements)))
626        
627          (for-each
628           (lambda (s)
629             (ly:set-option (car s) (cdr s)))
630           all-settings)
631          
632          (ly:clear-anonymous-modules)
633          (ly:set-option 'debug-gc-assert-parsed-dead #t)
634          (gc)
635          (ly:set-option 'debug-gc-assert-parsed-dead #f)
636          
637          
638          (if (ly:get-option 'debug-gc)
639              (dump-gc-protects)
640              (if (= (random 40) 1)
641                  (ly:reset-all-fonts)))))
642
643      files)
644
645     ;; we want the failed-files notice in the aggregrate logfile.
646     (if (ly:get-option 'separate-logs)
647         (ly:stderr-redirect
648          (if (string-or-symbol? (ly:get-option 'log-file))
649              (format "~a.log" (ly:get-option 'log-file))
650              "/dev/tty") "a"))
651
652     (if (ly:get-option 'dump-profile)
653         (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
654
655     failed))
656
657 (define (lilypond-file handler file-name)
658   (catch 'ly-file-failed
659          (lambda () (ly:parse-file file-name))
660          (lambda (x . args) (handler x file-name))))
661
662 (use-modules (scm editor))
663
664 (define-public (gui-main files)
665   (if (null? files)
666       (gui-no-files-handler))
667
668   (if (not (string? (ly:get-option 'log-file)))
669       (let* ((base (basename (car files) ".ly"))
670              (log-name (string-append base ".log")))
671         (if (not (ly:get-option 'gui))
672             (ly:message (_ "Redirecting output to ~a...") log-name))
673         (ly:stderr-redirect log-name "w")
674         (ly:message "# -*-compilation-*-"))
675     
676     (let ((failed (lilypond-all files)))
677       (if (pair? failed)
678           (begin
679             ;; ugh
680             (ly:stderr-redirect "foo" "r")
681             (system (get-editor-command log-name 0 0 0))
682             (ly:error (_ "failed files: ~S") (string-join failed))
683             ;; not reached?
684             (exit 1))
685           (exit 0)))))
686
687 (define (gui-no-files-handler)
688   (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
689          ;; FIXME: soft-code, localize
690          (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
691          (cmd (get-editor-command welcome-ly 0 0 0)))
692     (ly:message (_ "Invoking `~a'...") cmd)
693     (system cmd)
694     (exit 1)))