1 ;;;; This file is part of LilyPond, the GNU music typesetter.
3 ;;;; Copyright (C) 1998--2009 Jan Nieuwenhuizen <janneke@gnu.org>
4 ;;;; Han-Wen Nienhuys <hanwen@xs4all.nl>
6 ;;;; LilyPond is free software: you can redistribute it and/or modify
7 ;;;; it under the terms of the GNU General Public License as published by
8 ;;;; the Free Software Foundation, either version 3 of the License, or
9 ;;;; (at your option) any later version.
11 ;;;; LilyPond is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ;;;; GNU General Public License for more details.
16 ;;;; You should have received a copy of the GNU General Public License
17 ;;;; along with LilyPond. If not, see <http://www.gnu.org/licenses/>.
19 ;; Internationalisation: (_i "to be translated") gets an entry in the
20 ;; POT file; (gettext ...) must be invoked explicitly to do the actual
23 ;; (define-macro (_i x) x)
24 ;; (define-macro-public _i (x) x)
25 ;; (define-public-macro _i (x) x)
28 (defmacro-public _i (x) x)
30 (read-enable 'positions)
33 (define-public PLATFORM
36 (car (string-tokenize (utsname:sysname (uname)))))))
38 (define scheme-options-definitions
42 ;; - [subject-]object-object-verb +"ing"
43 ;; - [subject-]-verb-object-object
45 ;; Avoid overlong lines in `lilypond -dhelp'! Strings should not
46 ;; be longer than 48 characters per line.
49 "Render at higher resolution (using given factor)
50 and scale down result to prevent jaggies in
53 "Create .tex, .texi, .count files in the
56 "Select backend. Possible values: 'eps, 'null,
57 'ps, 'scm, 'socket, 'svg.")
58 (check-internal-types #f
59 "Check every property assignment for types.")
61 "Generate cut-out snippets of a score.")
63 "LilyPond prefix for data files (read-only).")
65 "Dump memory debugging statistics.")
66 (debug-gc-assert-parsed-dead #f
67 "For memory debugging: Ensure that all
68 references to parsed objects are dead. This is
69 an internal option, and is switched on
70 automatically for `-ddebug-gc'.")
72 "Debug the flex lexer.")
73 (debug-page-breaking-scoring #f
74 "Dump scores for many different page breaking
77 "Debug the bison parser.")
78 (debug-property-callbacks #f
79 "Debug cyclic callback chains.")
82 (delete-intermediate-files #t
83 "Delete unusable, intermediate PostScript files.")
85 "Dump memory and time information for each file.")
87 "Dump timing information (system-dependent).")
89 "Dump output signatures of each system. Used for
92 "Pad left edge of the output EPS bounding box by
93 given amount (in mm).")
95 "Load fonts via Ghostscript.")
96 (gs-load-lily-fonts #f
97 "Load only LilyPond fonts via Ghostscript.")
99 "Run LilyPond from a GUI and redirect stderr to
103 (include-book-title-preview #t
104 "Include book titles in preview images.")
105 (include-eps-fonts #t
106 "Include fonts in separate-system EPS files.")
108 "Process in parallel, using the given number of
111 "If string FOO is given as argument, redirect
112 output to log file `FOO.log'.")
113 (midi-extension ,(if (eq? PLATFORM 'windows)
116 "Set the default file extension for MIDI output
117 file to given string.")
119 "Make \\relative mode for simultaneous music work
120 similar to chord syntax.")
122 "Add point & click links to PDF output.")
124 "Set default paper size.")
125 (pixmap-format "png16m"
126 "Set GhostScript's output format for pixel images.")
128 "Create PNG and EPS preview images also.")
130 "Print pages in the normal way.")
131 (protected-scheme-parsing #t
132 "Continue when errors in inline scheme are caught
133 in the parser. If #f, halt on errors and print
135 (profile-property-accesses #f
136 "Keep statistics of get_property() calls.")
138 "Set resolution for generating PNG pixmaps to
139 given value (in dpi).")
141 "Specify name of a file which contains a list of
142 input files to be processed.")
143 (relative-includes #f
144 "When processing an \\include command, look for
145 the included file relative to the current file
146 (instead of the root file)")
148 "Run in safer mode.")
149 (strict-infinity-checking #f
150 "Force a crash on encountering Inf and NaN
151 floating point exceptions.")
153 "Don't use directories from input files while
154 constructing output file names.")
155 (separate-log-files #f
156 "For input files `FILE1.ly', `FILE2.ly', ...
157 output log data to files `FILE1.log',
159 (trace-memory-frequency #f
160 "Record Scheme cell usage this many times per
161 second. Dump results to `FILE.stacks' and
163 (trace-scheme-coverage #f
164 "Record coverage of Scheme files in `FILE.cov'.")
165 (show-available-fonts #f
166 "List available font names.")
167 (verbose ,(ly:command-line-verbose?)
168 "Value of the --verbose flag (read-only).")
170 "Change all warning and programming_error
171 messages into errors.")
174 ;; Need to do this in the beginning. Other parts of the Scheme
175 ;; initialization depend on these options.
177 (for-each (lambda (x)
178 (ly:add-option (car x) (cadr x) (caddr x)))
179 scheme-options-definitions)
181 (for-each (lambda (x)
182 (ly:set-option (car x) (cdr x)))
183 (eval-string (ly:command-line-options)))
187 (if (defined? 'set-debug-cell-accesses!)
188 (set-debug-cell-accesses! #f))
190 ;(set-debug-cell-accesses! 1000)
192 (use-modules (ice-9 regex)
205 (define-public fancy-format
208 (define-public (ergonomic-simple-format dest . rest)
209 "Like ice-9 format, but without the memory consumption."
211 (apply simple-format (cons #f (cons dest rest)))
212 (apply simple-format (cons dest rest))))
215 ergonomic-simple-format)
218 (define-public (myd k v)
225 (define-public (print . args)
226 (apply format (cons (current-output-port) args)))
229 ;;; General settings.
231 ;;; Debugging evaluator is slower. This should have a more sensible
234 (if (or (ly:get-option 'verbose)
235 (ly:get-option 'trace-memory-frequency)
236 (ly:get-option 'trace-scheme-coverage))
238 (ly:set-option 'protected-scheme-parsing #f)
239 (debug-enable 'debug)
240 (debug-enable 'backtrace)
241 (read-enable 'positions)))
243 (if (ly:get-option 'trace-scheme-coverage)
246 (define-public parser #f)
249 ;; gettext wrapper for guile < 1.7.2
250 (if (defined? 'gettext)
251 (define-public _ gettext)
252 (define-public _ ly:gettext))
254 (define-public (ly:load x)
255 (let* ((file-name (%search-load-path x)))
256 (if (ly:get-option 'verbose)
257 (ly:progress "[~A" file-name))
259 (ly:error (_ "cannot find: ~A") x))
260 (primitive-load file-name)
261 (if (ly:get-option 'verbose)
262 (ly:progress "]\n"))))
265 (let ((platform (string-tokenize
266 (vector-ref (uname) 0) char-set:letter+digit)))
267 (if (null? (cdr platform)) #f
268 (member (string-downcase (cadr platform)) '("95" "98" "me")))))
272 (define native-getcwd
276 (if (string-index x #\\)
278 (string-regexp-substitute
280 (string-regexp-substitute "\\\\" "/" x))))
282 ;; FIXME: this prints a warning.
283 (define-public (ly-getcwd)
284 (slashify (native-getcwd))))
287 (define-public ly-getcwd
290 (define-public (is-absolute? file-name)
291 (let ((file-name-length (string-length file-name)))
292 (if (= file-name-length 0)
294 (or (eq? (string-ref file-name 0) #\/)
295 (and (eq? PLATFORM 'windows)
296 (> file-name-length 2)
297 (eq? (string-ref file-name 1) #\:)
298 (eq? (string-ref file-name 2) #\/))))))
300 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
302 (define (type-check-list location signature arguments)
303 "Typecheck a list of arguments against a list of type predicates.
304 Print a message at LOCATION if any predicate failed."
305 (define (recursion-helper signature arguments count)
306 (define (helper pred? arg count)
307 (if (not (pred? arg))
312 #f (_ "wrong type for argument ~a. Expecting ~a, found ~s")
313 count (type-name pred?) arg))
317 (if (null? signature)
319 (and (helper (car signature) (car arguments) count)
320 (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
321 (recursion-helper signature arguments 1))
324 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
325 ;; Safe definitions utility
330 (define-macro (define-safe-public arglist . body)
331 "Define a variable, export it, and mark it as safe, i.e. usable in
332 LilyPond safe mode. The syntax is the same as `define*-public'."
333 (define (get-symbol arg)
335 (get-symbol (car arg))
338 (let ((safe-symbol (get-symbol arglist)))
340 (define*-public ,arglist
342 (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
346 (define-safe-public (lilypond-version)
348 (map (lambda (x) (if (symbol? x)
354 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
357 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
359 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
362 (define init-scheme-files
365 "define-event-classes.scm"
366 "define-music-types.scm"
369 "chord-ignatzek-names.scm"
371 "chord-generic-names.scm"
374 "music-functions.scm"
377 "define-music-properties.scm"
382 "parser-ly-from-scheme.scm"
383 "ly-syntax-constructors.scm"
385 "define-context-properties.scm"
386 "translation-functions.scm"
398 "predefined-fretboards.scm"
399 "define-markup-commands.scm"
400 "define-grob-properties.scm"
402 "define-grob-interfaces.scm"
403 "define-stencil-commands.scm"
407 "backend-library.scm"
411 ;; must be after everything has been defined
414 (for-each ly:load init-scheme-files)
416 (set! type-p-name-alist
417 `((,boolean? . "boolean")
418 (,boolean-or-symbol? . "boolean or symbol")
420 (,grob-list? . "list of grobs")
421 (,hash-table? . "hash table")
422 (,input-port? . "input port")
423 (,integer? . "integer")
425 (,ly:context? . "context")
426 (,ly:dimension? . "dimension, in staff space")
427 (,ly:dir? . "direction")
428 (,ly:duration? . "duration")
429 (,ly:font-metric? . "font metric")
430 (,ly:grob? . "layout object")
431 (,ly:grob-array? . "array of grobs")
432 (,ly:input-location? . "input location")
433 (,ly:moment? . "moment")
434 (,ly:music? . "music")
435 (,ly:music-list? . "list of music objects")
436 (,ly:music-output? . "music output")
437 (,ly:pitch? . "pitch")
438 (,ly:translator? . "translator")
439 (,ly:score? . "score")
440 (,ly:simple-closure? . "simple closure")
441 (,ly:skyline-pair? . "pair of skylines")
442 (,ly:stencil? . "stencil")
443 (,markup-list? . "list of markups")
444 (,markup? . "markup")
445 (,number-or-grob? . "number or grob")
446 (,number-or-string? . "number or string")
447 (,number-pair? . "pair of numbers")
448 (,number? . "number")
449 (,output-port? . "output port")
451 (,procedure? . "procedure")
452 (,rhythmic-location? . "rhythmic location")
453 (,scheme? . "any type")
454 (,string? . "string")
455 (,symbol? . "symbol")
456 (,vector? . "vector")))
458 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
461 (define (profile-measurements)
464 (list (- (+ (tms:cutime t)
466 (assoc-get 'gc-time-taken stats))
467 (assoc-get 'total-cells-allocated stats 0))))
469 (define (dump-profile base last this)
470 (let* ((outname (format "~a.profile" (dir-basename base ".ly")))
471 (diff (map (lambda (y) (apply - y)) (zip this last))))
472 (ly:progress "\nWriting timing to ~a..." outname)
473 (format (open-file outname "w")
474 "time: ~a\ncells: ~a\n"
475 (if (ly:get-option 'dump-cpu-profile)
480 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
481 ;; debug memory leaks
486 (define gc-protect-stat-count
489 (define-public (dump-live-object-stats outfile)
490 (for-each (lambda (x)
491 (format outfile "~a: ~a\n" (car x) (cdr x)))
492 (sort (gc-live-object-stats)
494 (string<? (car x) (car y))))))
496 (define-public (dump-gc-protects)
497 (set! gc-protect-stat-count (1+ gc-protect-stat-count))
498 (let* ((protects (sort (hash-table->alist (ly:protects))
500 (< (object-address (car a))
501 (object-address (car b))))))
502 (out-file-name (string-append
503 "gcstat-" (number->string gc-protect-stat-count)
505 (outfile (open-file out-file-name "w")))
507 (display (format "Dumping GC statistics ~a...\n" out-file-name))
508 (display (map (lambda (y)
512 (format "~a (~a) = ~a\n" (object-address x) c x)
516 (not (symbol? (car x))))
519 (format outfile "\nprotected symbols: ~a\n"
520 (apply + (map (lambda (obj-count)
521 (if (symbol? (car obj-count))
526 ;; (display (ly:smob-protects))
528 (if (defined? 'gc-live-object-stats)
530 (display "Live object statistics: GC'ing\n")
534 (display "Asserting dead objects\n")
535 (ly:set-option 'debug-gc-assert-parsed-dead #t)
537 (ly:set-option 'debug-gc-assert-parsed-dead #f)
538 (set! stats (gc-live-object-stats))
539 (display "Dumping live object statistics.\n")
540 (dump-live-object-stats outfile)))
542 (let* ((stats (gc-stats)))
543 (for-each (lambda (sym)
546 gc-protect-stat-count
548 (assoc-get sym stats "?"))
551 '(protected-objects bytes-malloced cell-heap-size)))
553 (close-port outfile)))
555 (define (check-memory)
556 "Read `/proc/self' to check up on memory use."
557 (define (gulp-file name)
558 (let* ((file (open-input-file name))
559 (text (read-delimited "" file)))
563 (let* ((stat (gulp-file "/proc/self/status"))
564 (lines (string-split stat #\newline))
565 (interesting (filter identity
568 (string-match "^VmData:[ \t]*([0-9]*) kB" l))
570 (mem (string->number (match:substring (car interesting) 1))))
571 (display (format "VMDATA: ~a\n" mem))
574 (begin (dump-gc-protects)
577 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
579 (define (multi-fork count)
580 "Split this process into COUNT helpers. Returns either a list of
581 PIDs or the number of the process."
582 (define (helper count acc)
584 (let* ((pid (primitive-fork)))
587 (helper (1- count) (cons pid acc))))
592 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
594 (define-public (lilypond-main files)
595 "Entry point for LilyPond."
596 (eval-string (ly:command-line-code))
597 (if (ly:get-option 'help)
598 (begin (ly:option-usage)
600 (if (ly:get-option 'show-available-fonts)
601 (begin (ly:font-config-display-fonts)
603 (if (ly:get-option 'gui)
608 (if (ly:get-option 'read-file-list)
611 (> (string-length s) 0))
614 (string-split (ly:gulp-file f) #\nl))
616 (if (and (number? (ly:get-option 'job-count))
617 (>= (length files) (ly:get-option 'job-count)))
618 (let* ((count (ly:get-option 'job-count))
619 (split-todo (split-list files count))
620 (joblist (multi-fork count))
622 (if (not (string-or-symbol? (ly:get-option 'log-file)))
623 (ly:set-option 'log-file "lilypond-multi-run"))
624 (if (number? joblist)
625 (begin (ly:set-option
626 'log-file (format "~a-~a"
627 (ly:get-option 'log-file) joblist))
628 (set! files (vector-ref split-todo joblist)))
629 (begin (ly:progress "\nForking into jobs: ~a\n" joblist)
632 (let* ((stat (cdr (waitpid pid))))
635 (acons (list-element-index joblist pid)
642 (logfile (format "~a-~a.log"
643 (ly:get-option 'log-file) job))
644 (log (ly:gulp-file logfile))
645 (len (string-length log))
646 (tail (substring log (max 0 (- len 1024)))))
647 (if (status:term-sig state)
650 (format (_ "job ~a terminated with signal: ~a")
651 job (status:term-sig state)))
653 (_ "logfile ~a (exit ~a):\n~a")
654 logfile (status:exit-val state) tail))))
657 (ly:error "Children ~a exited with errors."
659 ;; must overwrite individual entries
660 (if (ly:get-option 'dump-profile)
661 (dump-profile "lily-run-total"
662 '(0 0) (profile-measurements)))
663 (exit (if (null? errors)
666 (if (string-or-symbol? (ly:get-option 'log-file))
667 (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
668 (let ((failed (lilypond-all files)))
669 (if (ly:get-option 'trace-scheme-coverage)
671 (coverage:show-all (lambda (f)
672 (string-contains f "lilypond")))))
674 (begin (ly:error (_ "failed files: ~S") (string-join failed))
677 ;; HACK: be sure to exit with single newline
681 (define-public (lilypond-all files)
683 (separate-logs (ly:get-option 'separate-log-files))
686 (open-file (if (string-or-symbol? (ly:get-option 'log-file))
687 (format "~a.log" (ly:get-option 'log-file))
688 "/dev/tty") "a") #f))
689 (do-measurements (ly:get-option 'dump-profile))
690 (handler (lambda (key failed-file)
691 (set! failed (append (list failed-file) failed)))))
695 (let* ((start-measurements (if do-measurements
696 (profile-measurements)
698 (base (dir-basename x ".ly"))
699 (all-settings (ly:all-options)))
701 (ly:stderr-redirect (format "~a.log" base) "w"))
703 (format ping-log "Processing ~a\n" base))
704 (if (ly:get-option 'trace-memory-frequency)
705 (mtrace:start-trace (ly:get-option 'trace-memory-frequency)))
706 (lilypond-file handler x)
707 (if start-measurements
708 (dump-profile x start-measurements (profile-measurements)))
709 (if (ly:get-option 'trace-memory-frequency)
710 (begin (mtrace:stop-trace)
711 (mtrace:dump-results base)))
712 (for-each (lambda (s)
713 (ly:set-option (car s) (cdr s)))
715 (ly:clear-anonymous-modules)
716 (ly:set-option 'debug-gc-assert-parsed-dead #t)
718 (ly:set-option 'debug-gc-assert-parsed-dead #f)
719 (if (ly:get-option 'debug-gc)
721 (if (= (random 40) 1)
722 (ly:reset-all-fonts)))))
725 ;; we want the failed-files notice in the aggregrate logfile.
727 (format ping-log "Failed files: ~a\n" failed))
728 (if (ly:get-option 'dump-profile)
729 (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
732 (define (lilypond-file handler file-name)
733 (catch 'ly-file-failed
734 (lambda () (ly:parse-file file-name))
735 (lambda (x . args) (handler x file-name))))
737 (use-modules (scm editor))
739 (define-public (gui-main files)
741 (gui-no-files-handler))
742 (if (not (string? (ly:get-option 'log-file)))
743 (let* ((base (dir-basename (car files) ".ly"))
744 (log-name (string-append base ".log")))
745 (if (not (ly:get-option 'gui))
746 (ly:message (_ "Redirecting output to ~a...") log-name))
747 (ly:stderr-redirect log-name "w")
748 (ly:message "# -*-compilation-*-"))
749 (let ((failed (lilypond-all files)))
753 (ly:stderr-redirect "foo" "r")
754 (system (get-editor-command log-name 0 0 0))
755 (ly:error (_ "failed files: ~S") (string-join failed))
760 (define (gui-no-files-handler)
761 (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
762 ;; FIXME: soft-code, localize
763 (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
764 (cmd (get-editor-command welcome-ly 0 0 0)))
765 (ly:message (_ "Invoking `~a'...\n") cmd)