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