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