]> git.donarmstrong.com Git - lilypond.git/blob - scm/lily.scm
Proper loglevels: cmd-line option --loglevel=NONE/ERROR/WARN/BASIC/PROGRESS/DEBUG
[lilypond.git] / scm / lily.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 1998--2011 Jan Nieuwenhuizen <janneke@gnu.org>
4 ;;;; Han-Wen Nienhuys <hanwen@xs4all.nl>
5 ;;;;
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.
10 ;;;;
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.
15 ;;;;
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/>.
18
19 ;; Internationalisation: (_i "to be translated") gets an entry in the
20 ;; POT file; (gettext ...) must be invoked explicitly to do the actual
21 ;; "translation".
22 ;;
23 ;; (define-macro (_i x) x)
24 ;; (define-macro-public _i (x) x)
25 ;; (define-public-macro _i (x) x)
26 ;; Abbrv-PWR!
27
28 (defmacro-public _i (x) x)
29
30 ;;; Boolean thunk - are we integrating Guile V2.0 or higher with LilyPond?
31 (define-public (guile-v2)
32   (string>? (version) "1.9.10"))
33
34 (read-enable 'positions)
35 (if (not (guile-v2))
36     (debug-enable 'debug)
37     (begin
38       (debug-enable 'backtrace)
39       (debug-enable 'show-file-name)))
40
41 (define-public PLATFORM
42   (string->symbol
43    (string-downcase
44     (car (string-tokenize (utsname:sysname (uname)))))))
45
46 (define scheme-options-definitions
47   `(
48     ;; NAMING: either
49
50     ;; - [subject-]object-object-verb +"ing"
51     ;; - [subject-]-verb-object-object
52
53     ;; Avoid overlong lines in `lilypond -dhelp'!  Strings should not
54     ;; be longer than 48 characters per line.
55
56     (anti-alias-factor 1
57 "Render at higher resolution (using given factor)
58 and scale down result to prevent jaggies in
59 PNG images.")
60     (aux-files #t
61 "Create .tex, .texi, .count files in the
62 EPS backend.")
63     (backend ps
64 "Select backend.  Possible values: 'eps, 'null,
65 'ps, 'scm, 'socket, 'svg.")
66     (check-internal-types #f
67 "Check every property assignment for types.")
68     (clip-systems #f
69 "Generate cut-out snippets of a score.")
70     (datadir #f
71 "LilyPond prefix for data files (read-only).")
72     (debug-gc #f
73 "Dump memory debugging statistics.")
74     (debug-gc-assert-parsed-dead #f
75 "For memory debugging: Ensure that all
76 references to parsed objects are dead.  This is
77 an internal option, and is switched on
78 automatically for `-ddebug-gc'.")
79     (debug-lexer #f
80 "Debug the flex lexer.")
81     (debug-page-breaking-scoring #f
82 "Dump scores for many different page breaking
83 configurations.")
84     (debug-parser #f
85 "Debug the bison parser.")
86     (debug-property-callbacks #f
87 "Debug cyclic callback chains.")
88     (debug-skylines #f
89 "Debug skylines.")
90     (delete-intermediate-files #t
91 "Delete unusable, intermediate PostScript files.")
92     (dump-profile #f
93 "Dump memory and time information for each file.")
94     (dump-cpu-profile #f
95 "Dump timing information (system-dependent).")
96     (dump-signatures #f
97 "Dump output signatures of each system.  Used for
98 regression testing.")
99     (eps-box-padding #f
100 "Pad left edge of the output EPS bounding box by
101 given amount (in mm).")
102     (gs-load-fonts #f
103 "Load fonts via Ghostscript.")
104     (gs-load-lily-fonts #f
105 "Load only LilyPond fonts via Ghostscript.")
106     (gui #f
107 "Run LilyPond from a GUI and redirect stderr to
108 a log file.")
109     (help #f
110 "Show this help.")
111     (include-book-title-preview #t
112 "Include book titles in preview images.")
113     (include-eps-fonts #t
114 "Include fonts in separate-system EPS files.")
115     (include-settings #f
116 "Include file for global settings, included before the score is processed.")
117     (job-count #f
118 "Process in parallel, using the given number of
119 jobs.")
120     (log-file #f
121 "If string FOO is given as argument, redirect
122 output to log file `FOO.log'.")
123     (midi-extension ,(if (eq? PLATFORM 'windows)
124                          "mid"
125                          "midi")
126 "Set the default file extension for MIDI output
127 file to given string.")
128     (music-strings-to-paths #f
129 "Convert text strings to paths when glyphs belong
130 to a music font.")
131     (old-relative #f
132 "Make \\relative mode for simultaneous music work
133 similar to chord syntax.")
134     (point-and-click #t
135 "Add point & click links to PDF output.")
136     (paper-size "a4"
137 "Set default paper size.")
138     (pixmap-format "png16m"
139 "Set GhostScript's output format for pixel images.")
140     (preview #f
141 "Create preview images also.")
142     (print-pages #t
143 "Print pages in the normal way.")
144     (protected-scheme-parsing #t
145 "Continue when errors in inline scheme are caught
146 in the parser.  If #f, halt on errors and print
147 a stack trace.")
148     (profile-property-accesses #f
149 "Keep statistics of get_property() calls.")
150     (resolution 101
151 "Set resolution for generating PNG pixmaps to
152 given value (in dpi).")
153     (read-file-list #f
154 "Specify name of a file which contains a list of
155 input files to be processed.")
156     (relative-includes #f
157 "When processing an \\include command, look for
158 the included file relative to the current file
159 (instead of the root file)")
160     (safe #f
161 "Run in safer mode.")
162     (separate-log-files #f
163 "For input files `FILE1.ly', `FILE2.ly', ...
164 output log data to files `FILE1.log',
165 `FILE2.log', ...")
166     (show-available-fonts #f
167 "List available font names.")
168     (strict-infinity-checking #f
169 "Force a crash on encountering Inf and NaN
170 floating point exceptions.")
171     (strip-output-dir #t
172 "Don't use directories from input files while
173 constructing output file names.")
174     (svg-woff #f
175 "Use woff font files in SVG backend.")
176     (trace-memory-frequency #f
177 "Record Scheme cell usage this many times per
178 second.  Dump results to `FILE.stacks' and
179 `FILE.graph'.")
180     (trace-scheme-coverage #f
181 "Record coverage of Scheme files in `FILE.cov'.")
182     (verbose ,(ly:verbose-output?)
183 "Verbose output, i.e. loglevel at least DEBUG (read-only).")
184     (warning-as-error #f
185 "Change all warning and programming_error
186 messages into errors.")
187     ))
188
189 ;; Need to do this in the beginning.  Other parts of the Scheme
190 ;; initialization depend on these options.
191
192 (for-each (lambda (x)
193             (ly:add-option (car x) (cadr x) (caddr x)))
194           scheme-options-definitions)
195
196 (for-each (lambda (x)
197             (ly:set-option (car x) (cdr x)))
198           (eval-string (ly:command-line-options)))
199
200 (debug-set! stack 0)
201
202 (if (defined? 'set-debug-cell-accesses!)
203     (set-debug-cell-accesses! #f))
204
205 ;;(set-debug-cell-accesses! 1000)
206
207 (use-modules (ice-9 regex)
208              (ice-9 safe)
209              (ice-9 format)
210              (ice-9 rdelim)
211              (ice-9 optargs)
212              (oop goops)
213              (srfi srfi-1)
214              (srfi srfi-13)
215              (srfi srfi-14)
216              (scm clip-region)
217              (scm memory-trace)
218              (scm coverage))
219
220 (define-public _ gettext)
221 ;;; There are new modules defined in Guile V2.0 which we need to use.
222 ;;
223 ;;  Modules and scheme files loaded by lily.scm use currying
224 ;;  in Guile V2 this needs a module which is not present in Guile V1.8
225 ;;
226
227 (cond
228   ((guile-v2)
229    (ly:debug (_ "Using (ice-9 curried-definitions) module\n"))
230    (use-modules (ice-9 curried-definitions)))
231   (else
232     (ly:debug (_ "Guile 1.8\n"))))
233
234 ;; TODO add in modules for V1.8.7 deprecated in V2.0 and integrated
235 ;; into Guile base code, like (ice-9 syncase).
236 ;;
237
238 (define-public fancy-format
239   format)
240
241 (define-public (ergonomic-simple-format dest . rest)
242   "Like ice-9's @code{format}, but without the memory consumption."
243   (if (string? dest)
244       (apply simple-format (cons #f (cons dest rest)))
245       (apply simple-format (cons dest rest))))
246
247 (define format
248   ergonomic-simple-format)
249
250 ;; my display
251 (define-public (myd k v)
252   (display k)
253   (display ": ")
254   (display v)
255   (display ", ")
256   v)
257
258 (define-public (print . args)
259   (apply format (cons (current-output-port) args)))
260
261
262 ;;; General settings.
263 ;;;
264 ;;; Debugging evaluator is slower.  This should have a more sensible
265 ;;; default.
266
267 (if (or (ly:get-option 'verbose)
268         (ly:get-option 'trace-memory-frequency)
269         (ly:get-option 'trace-scheme-coverage))
270     (begin
271       (ly:set-option 'protected-scheme-parsing #f)
272       (debug-enable 'backtrace)
273       (read-enable 'positions)))
274
275 (if (ly:get-option 'trace-scheme-coverage)
276     (coverage:enable))
277
278 (define-public parser #f)
279
280 (define music-string-to-path-backends
281   '(svg))
282
283 (if (memq (ly:get-option 'backend) music-string-to-path-backends)
284     (ly:set-option 'music-strings-to-paths #t))
285
286
287 (define-public (ly:load x)
288   (let* ((file-name (%search-load-path x)))
289     (ly:debug "[~A" file-name)
290     (if (not file-name)
291         (ly:error (_ "cannot find: ~A") x))
292     (primitive-load-path file-name)  ;; to support Guile V2 autocompile
293     ;; TODO: Any chance to use ly:debug here? Need to extend it to prevent
294     ;;       a newline in this case
295     (if (ly:get-option 'verbose)
296         (ly:progress "]\n"))))
297
298 (define-public DOS
299   (let ((platform (string-tokenize
300                    (vector-ref (uname) 0) char-set:letter+digit)))
301     (if (null? (cdr platform)) #f
302         (member (string-downcase (cadr platform)) '("95" "98" "me")))))
303
304 (define (slashify x)
305   (if (string-index x #\\)
306       x
307       (string-regexp-substitute
308         "//*" "/"
309         (string-regexp-substitute "\\\\" "/" x))))
310
311 (define-public (ly-getcwd)
312   (if (eq? PLATFORM 'windows)
313       (slashify (getcwd))
314       (getcwd)))
315
316 (define-public (is-absolute? file-name)
317   (let ((file-name-length (string-length file-name)))
318     (if (= file-name-length 0)
319         #f
320         (or (eq? (string-ref file-name 0) #\/)
321             (and (eq? PLATFORM 'windows)
322                  (> file-name-length 2)
323                  (eq? (string-ref file-name 1) #\:)
324                  (eq? (string-ref file-name 2) #\/))))))
325
326 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
327 ;;; If necessary, emulate Guile V2 module_export_all! for Guile V1.8.n
328 (cond-expand
329  ((not guile-v2)
330   (define (module-export-all! mod)
331     (define (fresh-interface!)
332       (let ((iface (make-module)))
333         (set-module-name! iface (module-name mod))
334         ;; for guile 2: (set-module-version! iface (module-version mod))
335         (set-module-kind! iface 'interface)
336         (set-module-public-interface! mod iface)
337         iface))
338     (let ((iface (or (module-public-interface mod)
339                      (fresh-interface!))))
340       (set-module-obarray! iface (module-obarray mod))))))
341
342 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
343 (define (type-check-list location signature arguments)
344   "Typecheck a list of arguments against a list of type predicates.
345 Print a message at LOCATION if any predicate failed."
346   (define (recursion-helper signature arguments count)
347     (define (helper pred? arg count)
348       (if (not (pred? arg))
349           (begin
350             (ly:input-message
351              location
352              (format
353               #f (_ "wrong type for argument ~a.  Expecting ~a, found ~s")
354               count (type-name pred?) arg))
355             #f)
356           #t))
357
358     (if (null? signature)
359         #t
360         (and (helper (car signature) (car arguments) count)
361              (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
362   (recursion-helper signature arguments 1))
363
364
365 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
366 ;; Safe definitions utility
367
368 (define safe-objects
369   (list))
370
371 (define-macro (define-safe-public arglist . body)
372   "Define a variable, export it, and mark it as safe, i.e. usable in
373 LilyPond safe mode.  The syntax is the same as `define*-public'."
374   (define (get-symbol arg)
375     (if (pair? arg)
376         (get-symbol (car arg))
377         arg))
378
379   (let ((safe-symbol (get-symbol arglist)))
380     `(begin
381        (define*-public ,arglist
382          ,@body)
383        (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
384                                 safe-objects))
385        ,safe-symbol)))
386
387 (define-safe-public (lilypond-version)
388   (string-join
389    (map (lambda (x) (if (symbol? x)
390                         (symbol->string x)
391                         (number->string x)))
392         (ly:version))
393    "."))
394
395 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
396 ;; init pitch system
397
398 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
399
400 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
401 ;; other files.
402
403 (define init-scheme-files
404   '("lily-library.scm"
405     "file-cache.scm"
406     "define-event-classes.scm"
407     "define-music-callbacks.scm"
408     "define-music-types.scm"
409     "define-note-names.scm"
410     "output-lib.scm"
411     "c++.scm"
412     "chord-ignatzek-names.scm"
413     "chord-entry.scm"
414     "chord-generic-names.scm"
415     "stencil.scm"
416     "markup.scm"
417     "modal-transforms.scm"
418     "music-functions.scm"
419     "part-combiner.scm"
420     "autochange.scm"
421     "define-music-properties.scm"
422     "time-signature-settings.scm"
423     "auto-beam.scm"
424     "bezier-tools.scm"
425     "parser-ly-from-scheme.scm"
426     "ly-syntax-constructors.scm"
427
428     "define-context-properties.scm"
429     ;; guile 1.9 wants markups defined before referenced
430     "define-markup-commands.scm"
431
432     "chord-name.scm"
433     "translation-functions.scm"
434     "script.scm"
435     "midi.scm"
436     "layout-beam.scm"
437     "parser-clef.scm"
438     "layout-slur.scm"
439     "font.scm"
440     "encoding.scm"
441
442     "flag-styles.scm"
443     "fret-diagrams.scm"
444     "tablature.scm"
445     "harp-pedals.scm"
446     "define-woodwind-diagrams.scm"
447     "display-woodwind-diagrams.scm"
448     "predefined-fretboards.scm"
449     "define-grob-properties.scm"
450     "define-grobs.scm"
451     "define-grob-interfaces.scm"
452     "define-stencil-commands.scm"
453     "titling.scm"
454
455     "paper.scm"
456     "backend-library.scm"
457     "x11-color.scm"
458
459     ;; must be after everything has been defined
460     "safe-lily.scm"))
461
462 (for-each ly:load init-scheme-files)
463
464 (define-public r5rs-primary-predicates
465   `((,boolean? . "boolean")
466     (,char? . "character")
467     (,number? . "number")
468     (,pair? . "pair")
469     (,port? . "port")
470     (,procedure? . "procedure")
471     (,string? . "string")
472     (,symbol? . "symbol")
473     (,vector? . "vector")))
474
475 (define-public r5rs-secondary-predicates
476   `((,char-alphabetic? . "alphabetic character")
477     (,char-lower-case? . "lower-case character")
478     (,char-numeric? . "numeric character")
479     (,char-upper-case? . "upper-case character")
480     (,char-whitespace? . "whitespace character")
481
482     (,complex? . "complex number")
483     (,even? . "even number")
484     (,exact? . "exact number")
485     (,inexact? . "inexact number")
486     (,integer? . "integer")
487     (,negative? . "negative number")
488     (,odd? . "odd number")
489     (,positive? . "positive number")
490     (,rational? . "rational number")
491     (,real? . "real number")
492     (,zero? . "zero")
493
494     (,list? . "list")
495     (,null? . "null")
496
497     (,input-port? . "input port")
498     (,output-port? . "output port")
499
500     ;; would this ever be used?
501     (,eof-object? . "end-of-file object")
502     ))
503
504 (define-public guile-predicates
505   `((,hash-table? . "hash table")
506   ))
507
508 (define-public lilypond-scheme-predicates
509   `((,boolean-or-symbol? . "boolean or symbol")
510     (,color? . "color")
511     (,cheap-list? . "list")
512     (,grob-list? . "list of grobs")
513     ;; this is built on cheap-list
514     (,list-or-symbol? . "list or symbol")
515     (,markup? . "markup")
516     (,markup-command-list? . "markup command list")
517     (,markup-list? . "markup list")
518     (,moment-pair? . "pair of moment objects")
519     (,number-or-grob? . "number or grob")
520     (,number-or-pair? . "number or pair")
521     (,number-or-string? . "number or string")
522     (,number-pair? . "pair of numbers")
523     (,rhythmic-location? . "rhythmic location")
524     (,scheme? . "any type")
525     (,string-or-pair? . "string or pair")
526     (,string-or-symbol? . "string or symbol")
527     ))
528
529 (define-public lilypond-exported-predicates
530   `((,ly:box? . "box")
531     (,ly:context? . "context")
532     (,ly:dimension? . "dimension, in staff space")
533     (,ly:dir? . "direction")
534     (,ly:dispatcher? . "dispatcher")
535     (,ly:duration? . "duration")
536     (,ly:font-metric? . "font metric")
537     (,ly:grob? . "graphical (layout) object")
538     (,ly:grob-array? . "array of grobs")
539     (,ly:input-location? . "input location")
540     (,ly:item? . "item")
541     (,ly:iterator? . "iterator")
542     (,ly:lily-lexer? . "lily-lexer")
543     (,ly:lily-parser? . "lily-parser")
544     (,ly:listener? . "listener")
545     (,ly:moment? . "moment")
546     (,ly:music? . "music")
547     (,ly:music-function? . "music function")
548     (,ly:music-list? . "list of music objects")
549     (,ly:music-output? . "music output")
550     (,ly:otf-font? . "OpenType font")
551     (,ly:output-def? . "output definition")
552     (,ly:page-marker? . "page marker")
553     (,ly:pango-font? . "pango font")
554     (,ly:paper-book? . "paper book")
555     (,ly:paper-system? . "paper-system Prob")
556     (,ly:pitch? . "pitch")
557     (,ly:prob? . "property object")
558     (,ly:score? . "score")
559     (,ly:simple-closure? . "simple closure")
560     (,ly:skyline? . "skyline")
561     (,ly:skyline-pair? . "pair of skylines")
562     (,ly:source-file? . "source file")
563     (,ly:spanner? . "spanner")
564     (,ly:stencil? . "stencil")
565     (,ly:stream-event? . "stream event")
566     (,ly:translator? . "translator")
567     (,ly:translator-group? . "translator group")
568     ))
569
570
571 (set! type-p-name-alist
572       (append r5rs-primary-predicates
573               r5rs-secondary-predicates
574               guile-predicates
575               lilypond-scheme-predicates
576               lilypond-exported-predicates))
577
578
579 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
580 ;; timing
581
582 (define (profile-measurements)
583   (let* ((t (times))
584          (stats (gc-stats)))
585     (list (- (+ (tms:cutime t)
586                 (tms:utime t))
587              (assoc-get 'gc-time-taken stats))
588           (assoc-get 'total-cells-allocated  stats 0))))
589
590 (define (dump-profile base last this)
591   (let* ((outname (format #f "~a.profile" (dir-basename base ".ly")))
592          (diff (map (lambda (y) (apply - y)) (zip this last))))
593     (ly:progress "\nWriting timing to ~a..." outname)
594     (format (open-file outname "w")
595             "time: ~a\ncells: ~a\n"
596             (if (ly:get-option 'dump-cpu-profile)
597                 (car diff)
598                 0)
599             (cadr diff))))
600
601 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
602 ;; debug memory leaks
603
604 (define gc-dumping
605   #f)
606
607 (define gc-protect-stat-count
608   0)
609
610 (define-public (dump-live-object-stats outfile)
611   (for-each (lambda (x)
612               (format outfile "~a: ~a\n" (car x) (cdr x)))
613             (sort (gc-live-object-stats)
614                   (lambda (x y)
615                     (string<? (car x) (car y))))))
616
617 (define-public (dump-gc-protects)
618   (set! gc-protect-stat-count (1+ gc-protect-stat-count))
619   (let* ((protects (sort (hash-table->alist (ly:protects))
620                          (lambda (a b)
621                            (< (object-address (car a))
622                               (object-address (car b))))))
623          (out-file-name (string-append
624                          "gcstat-" (number->string gc-protect-stat-count)
625                          ".scm"))
626          (outfile (open-file out-file-name "w")))
627     (set! gc-dumping #t)
628     (format #t "Dumping GC statistics ~a...\n" out-file-name)
629     (for-each (lambda (y)
630                 (let ((x (car y))
631                       (c (cdr y)))
632                   (format outfile "~a (~a) = ~a\n" (object-address x) c x)))
633               (filter
634                (lambda (x)
635                  (not (symbol? (car x))))
636                protects))
637     (format outfile "\nprotected symbols: ~a\n"
638             (apply + (map (lambda (obj-count)
639                             (if (symbol? (car obj-count))
640                                 (cdr obj-count)
641                                 0))
642                           protects)))
643
644     ;; (display (ly:smob-protects))
645     (newline outfile)
646     (if (defined? 'gc-live-object-stats)
647         (let* ((stats #f))
648           (display "Live object statistics: GC'ing\n")
649           (ly:reset-all-fonts)
650           (gc)
651           (gc)
652           (display "Asserting dead objects\n")
653           (ly:set-option 'debug-gc-assert-parsed-dead #t)
654           (gc)
655           (ly:set-option 'debug-gc-assert-parsed-dead #f)
656           (set! stats (gc-live-object-stats))
657           (display "Dumping live object statistics.\n")
658           (dump-live-object-stats outfile)))
659     (newline outfile)
660     (let* ((stats (gc-stats)))
661       (for-each (lambda (sym)
662                   (format outfile "~a ~a ~a\n"
663                           gc-protect-stat-count
664                           sym
665                           (assoc-get sym stats "?")))
666                 '(protected-objects bytes-malloced cell-heap-size)))
667     (set! gc-dumping #f)
668     (close-port outfile)))
669
670 (define (check-memory)
671   "Read `/proc/self' to check up on memory use."
672   (define (gulp-file name)
673     (let* ((file (open-input-file name))
674            (text (read-delimited "" file)))
675       (close file)
676       text))
677
678   (let* ((stat (gulp-file "/proc/self/status"))
679          (lines (string-split stat #\newline))
680          (interesting (filter identity
681                               (map
682                                (lambda (l)
683                                  (string-match "^VmData:[ \t]*([0-9]*) kB" l))
684                                lines)))
685          (mem (string->number (match:substring (car interesting) 1))))
686     (format #t "VMDATA: ~a\n" mem)
687     (display (gc-stats))
688     (if (> mem 100000)
689         (begin (dump-gc-protects)
690                (raise 1)))))
691
692 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
693
694 (define (multi-fork count)
695   "Split this process into COUNT helpers.  Returns either a list of
696 PIDs or the number of the process."
697   (define (helper count acc)
698     (if (> count 0)
699         (let* ((pid (primitive-fork)))
700           (if (= pid 0)
701               (1- count)
702               (helper (1- count) (cons pid acc))))
703         acc))
704
705   (helper count '()))
706
707 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
708
709 (define* (ly:exit status #:optional (silently #f))
710   "Exit function for lilypond"
711   (if (not silently)
712       (case status
713         ((0) (ly:success (_ "Compilation successfully completed")))
714         ((1) (ly:warning (_ "Compilation completed with warnings or errors")))
715         (else (ly:message ""))))
716   (exit status))
717
718 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
719
720 (define-public (lilypond-main files)
721   "Entry point for LilyPond."
722   (eval-string (ly:command-line-code))
723   (if (ly:get-option 'help)
724       (begin (ly:option-usage)
725              (ly:exit 0 #t)))
726   (if (ly:get-option 'show-available-fonts)
727       (begin (ly:font-config-display-fonts)
728              (ly:exit 0 #t)))
729   (if (ly:get-option 'gui)
730       (gui-main files))
731   (if (null? files)
732       (begin (ly:usage)
733              (ly:exit 2 #t)))
734   (if (ly:get-option 'read-file-list)
735       (set! files
736             (filter (lambda (s)
737                       (> (string-length s) 0))
738                     (apply append
739                            (map (lambda (f)
740                                   (string-split (ly:gulp-file f) #\nl))
741                                 files)))))
742   (if (and (number? (ly:get-option 'job-count))
743            (>= (length files) (ly:get-option 'job-count)))
744       (let* ((count (ly:get-option 'job-count))
745              (split-todo (split-list files count))
746              (joblist (multi-fork count))
747              (errors '()))
748         (if (not (string-or-symbol? (ly:get-option 'log-file)))
749             (ly:set-option 'log-file "lilypond-multi-run"))
750         (if (number? joblist)
751             (begin (ly:set-option
752                     'log-file (format #f "~a-~a"
753                                       (ly:get-option 'log-file) joblist))
754                    (set! files (vector-ref split-todo joblist)))
755             (begin (ly:progress "\nForking into jobs:  ~a\n" joblist)
756                    (for-each
757                     (lambda (pid)
758                       (let* ((stat (cdr (waitpid pid))))
759                         (if (not (= stat 0))
760                             (set! errors
761                                   (acons (list-element-index joblist pid)
762                                          stat errors)))))
763                     joblist)
764                    (for-each
765                     (lambda (x)
766                       (let* ((job (car x))
767                              (state (cdr x))
768                              (logfile (format #f "~a-~a.log"
769                                               (ly:get-option 'log-file) job))
770                              (log (ly:gulp-file logfile))
771                              (len (string-length log))
772                              (tail (substring  log (max 0 (- len 1024)))))
773                         (if (status:term-sig state)
774                             (ly:message
775                              "\n\n~a\n"
776                              (format #f (_ "job ~a terminated with signal: ~a")
777                                      job (status:term-sig state)))
778                             (ly:message
779                              (_ "logfile ~a (exit ~a):\n~a")
780                              logfile (status:exit-val state) tail))))
781                     errors)
782                    (if (pair? errors)
783                        (ly:error "Children ~a exited with errors."
784                                  (map car errors)))
785                    ;; must overwrite individual entries
786                    (if (ly:get-option 'dump-profile)
787                        (dump-profile "lily-run-total"
788                                      '(0 0) (profile-measurements)))
789                    (if (null? errors)
790                        (ly:exit 0 #f)
791                        (ly:exit 1 #f))))))
792
793   (if (string-or-symbol? (ly:get-option 'log-file))
794       (ly:stderr-redirect (format #f "~a.log" (ly:get-option 'log-file)) "w"))
795   (let ((failed (lilypond-all files)))
796     (if (ly:get-option 'trace-scheme-coverage)
797         (begin
798           (coverage:show-all (lambda (f)
799                                (string-contains f "lilypond")))))
800     (if (pair? failed)
801         (begin (ly:error (_ "failed files: ~S") (string-join failed))
802                (ly:exit 1 #f))
803         (begin
804           (ly:exit 0 #f)))))
805
806
807 (define-public (lilypond-all files)
808   (let* ((failed '())
809          (separate-logs (ly:get-option 'separate-log-files))
810          (ping-log
811           (if separate-logs
812               (open-file (if (string-or-symbol? (ly:get-option 'log-file))
813                              (format #f "~a.log" (ly:get-option 'log-file))
814                              "/dev/stderr") "a") #f))
815          (do-measurements (ly:get-option 'dump-profile))
816          (handler (lambda (key failed-file)
817                     (set! failed (append (list failed-file) failed)))))
818     (gc)
819     (for-each
820      (lambda (x)
821        (let* ((start-measurements (if do-measurements
822                                       (profile-measurements)
823                                       #f))
824               (base (dir-basename x ".ly"))
825               (all-settings (ly:all-options)))
826          (if separate-logs
827              (ly:stderr-redirect (format #f "~a.log" base) "w"))
828          (if ping-log
829              (format ping-log "Processing ~a\n" base))
830          (if (ly:get-option 'trace-memory-frequency)
831              (mtrace:start-trace  (ly:get-option 'trace-memory-frequency)))
832          (lilypond-file handler x)
833          (if start-measurements
834              (dump-profile x start-measurements (profile-measurements)))
835          (if (ly:get-option 'trace-memory-frequency)
836              (begin (mtrace:stop-trace)
837                     (mtrace:dump-results base)))
838          (for-each (lambda (s)
839                      (ly:set-option (car s) (cdr s)))
840                    all-settings)
841          (ly:set-option 'debug-gc-assert-parsed-dead #t)
842          (gc)
843          (ly:set-option 'debug-gc-assert-parsed-dead #f)
844          (if (ly:get-option 'debug-gc)
845              (dump-gc-protects)
846              (ly:reset-all-fonts))))
847      files)
848
849     ;; Ensure a notice re failed files is written to aggregate logfile.
850     (if ping-log
851         (format ping-log "Failed files: ~a\n" failed))
852     (if (ly:get-option 'dump-profile)
853         (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
854     failed))
855
856 (define (lilypond-file handler file-name)
857   (catch 'ly-file-failed
858          (lambda () (ly:parse-file file-name))
859          (lambda (x . args) (handler x file-name))))
860
861 (use-modules (scm editor))
862
863 (define-public (gui-main files)
864   (if (null? files)
865       (gui-no-files-handler))
866   (if (not (string? (ly:get-option 'log-file)))
867       (let* ((base (dir-basename (car files) ".ly"))
868              (log-name (string-append base ".log")))
869         (if (not (ly:get-option 'gui))
870             (ly:message (_ "Redirecting output to ~a...") log-name))
871         (ly:stderr-redirect log-name "w")
872         (ly:message "# -*-compilation-*-"))
873       (let ((failed (lilypond-all files)))
874         (if (pair? failed)
875             (begin
876               ;; ugh
877               (ly:stderr-redirect "foo" "r")
878               (system (get-editor-command log-name 0 0 0))
879               (ly:error (_ "failed files: ~S") (string-join failed))
880               ;; not reached?
881               (exit 1))
882             (ly:exit 0 #f)))))
883
884 (define (gui-no-files-handler)
885   (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
886          ;; FIXME: soft-code, localize
887          (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
888          (cmd (get-editor-command welcome-ly 0 0 0)))
889     (ly:message (_ "Invoking `~a'...\n") cmd)
890     (system cmd)
891     (ly:exit 1 #f)))