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