]> git.donarmstrong.com Git - lilypond.git/blob - scm/lily.scm
Doc & scm/: Music-functions and type-predicates.
[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     (show-available-fonts #f
169 "List available font names.")
170     (verbose ,(ly:command-line-verbose?)
171 "Value of the --verbose flag (read-only).")
172     (warning-as-error #f
173 "Change all warning and programming_error
174 messages into errors.")
175     ))
176
177 ;; Need to do this in the beginning.  Other parts of the Scheme
178 ;; initialization depend on these options.
179
180 (for-each (lambda (x)
181             (ly:add-option (car x) (cadr x) (caddr x)))
182           scheme-options-definitions)
183
184 (for-each (lambda (x)
185             (ly:set-option (car x) (cdr x)))
186           (eval-string (ly:command-line-options)))
187
188 (debug-set! stack 0)
189
190 (if (defined? 'set-debug-cell-accesses!)
191     (set-debug-cell-accesses! #f))
192
193                                         ;(set-debug-cell-accesses! 1000)
194
195 (use-modules (ice-9 regex)
196               (ice-9 safe)
197               (ice-9 format)
198               (ice-9 rdelim)
199               (ice-9 optargs)
200               (oop goops)
201               (srfi srfi-1)
202               (srfi srfi-13)
203               (srfi srfi-14)
204               (scm clip-region)
205               (scm memory-trace)
206               (scm coverage))
207
208 (define-public fancy-format
209   format)
210
211 (define-public (ergonomic-simple-format dest . rest)
212   "Like ice-9 format, but without the memory consumption."
213   (if (string? dest)
214       (apply simple-format (cons #f (cons dest rest)))
215       (apply simple-format (cons dest rest))))
216
217 (define format
218   ergonomic-simple-format)
219
220 ;; my display
221 (define-public (myd k v)
222   (display k)
223   (display ": ")
224   (display v)
225   (display ", ")
226   v)
227
228 (define-public (print . args)
229   (apply format (cons (current-output-port) args)))
230
231
232 ;;; General settings.
233 ;;;
234 ;;; Debugging evaluator is slower.  This should have a more sensible
235 ;;; default.
236
237 (if (or (ly:get-option 'verbose)
238         (ly:get-option 'trace-memory-frequency)
239         (ly:get-option 'trace-scheme-coverage))
240     (begin
241       (ly:set-option 'protected-scheme-parsing #f)
242       (debug-enable 'debug)
243       (debug-enable 'backtrace)
244       (read-enable 'positions)))
245
246 (if (ly:get-option 'trace-scheme-coverage)
247     (coverage:enable))
248
249 (define-public parser #f)
250
251 (define music-string-to-path-backends
252   '(svg))
253
254 (if (memq (ly:get-option 'backend) music-string-to-path-backends)
255     (ly:set-option 'music-strings-to-paths #t))
256
257 (define-public _ gettext)
258
259 (define-public (ly:load x)
260   (let* ((file-name (%search-load-path x)))
261     (if (ly:get-option 'verbose)
262         (ly:progress "[~A" file-name))
263     (if (not file-name)
264         (ly:error (_ "cannot find: ~A") x))
265     (primitive-load file-name)
266     (if (ly:get-option 'verbose)
267         (ly:progress "]\n"))))
268
269 (define-public DOS
270   (let ((platform (string-tokenize
271                    (vector-ref (uname) 0) char-set:letter+digit)))
272     (if (null? (cdr platform)) #f
273         (member (string-downcase (cadr platform)) '("95" "98" "me")))))
274
275 (define (slashify x)
276   (if (string-index x #\\)
277       x
278       (string-regexp-substitute
279         "//*" "/"
280         (string-regexp-substitute "\\\\" "/" x))))
281
282 (define-public (ly-getcwd)
283   (if (eq? PLATFORM 'windows)
284       (slashify (getcwd))
285       (getcwd)))
286
287 (define-public (is-absolute? file-name)
288   (let ((file-name-length (string-length file-name)))
289     (if (= file-name-length 0)
290         #f
291         (or (eq? (string-ref file-name 0) #\/)
292             (and (eq? PLATFORM 'windows)
293                  (> file-name-length 2)
294                  (eq? (string-ref file-name 1) #\:)
295                  (eq? (string-ref file-name 2) #\/))))))
296
297 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
298
299 (define (type-check-list location signature arguments)
300   "Typecheck a list of arguments against a list of type predicates.
301 Print a message at LOCATION if any predicate failed."
302   (define (recursion-helper signature arguments count)
303     (define (helper pred? arg count)
304       (if (not (pred? arg))
305           (begin
306             (ly:input-message
307              location
308              (format
309               #f (_ "wrong type for argument ~a.  Expecting ~a, found ~s")
310               count (type-name pred?) arg))
311             #f)
312           #t))
313
314     (if (null? signature)
315         #t
316         (and (helper (car signature) (car arguments) count)
317              (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
318   (recursion-helper signature arguments 1))
319
320
321 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
322 ;; Safe definitions utility
323
324 (define safe-objects
325   (list))
326
327 (define-macro (define-safe-public arglist . body)
328   "Define a variable, export it, and mark it as safe, i.e. usable in
329 LilyPond safe mode.  The syntax is the same as `define*-public'."
330   (define (get-symbol arg)
331     (if (pair? arg)
332         (get-symbol (car arg))
333         arg))
334
335   (let ((safe-symbol (get-symbol arglist)))
336     `(begin
337        (define*-public ,arglist
338          ,@body)
339        (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
340                                 safe-objects))
341        ,safe-symbol)))
342
343 (define-safe-public (lilypond-version)
344   (string-join
345    (map (lambda (x) (if (symbol? x)
346                         (symbol->string x)
347                         (number->string x)))
348         (ly:version))
349    "."))
350
351 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
352 ;; init pitch system
353
354 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
355
356 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
357 ;; other files.
358
359 (define init-scheme-files
360   '("lily-library.scm"
361     "file-cache.scm"
362     "define-event-classes.scm"
363     "define-music-types.scm"
364     "output-lib.scm"
365     "c++.scm"
366     "chord-ignatzek-names.scm"
367     "chord-entry.scm"
368     "chord-generic-names.scm"
369     "stencil.scm"
370     "markup.scm"
371     "music-functions.scm"
372     "part-combiner.scm"
373     "autochange.scm"
374     "define-music-properties.scm"
375     "beam-settings.scm"
376     "auto-beam.scm"
377     "chord-name.scm"
378
379     "parser-ly-from-scheme.scm"
380     "ly-syntax-constructors.scm"
381
382     "define-context-properties.scm"
383     "translation-functions.scm"
384     "script.scm"
385     "midi.scm"
386     "layout-beam.scm"
387     "parser-clef.scm"
388     "layout-slur.scm"
389     "font.scm"
390     "encoding.scm"
391
392     "flag-styles.scm"
393     "fret-diagrams.scm"
394     "harp-pedals.scm"
395     "predefined-fretboards.scm"
396     "define-markup-commands.scm"
397     "define-grob-properties.scm"
398     "define-grobs.scm"
399     "define-grob-interfaces.scm"
400     "define-stencil-commands.scm"
401     "titling.scm"
402
403     "paper.scm"
404     "backend-library.scm"
405     "x11-color.scm"
406     "tablature.scm"
407
408     ;; must be after everything has been defined
409     "safe-lily.scm"))
410
411 (for-each ly:load init-scheme-files)
412
413 (define-public r5rs-primary-predicates
414   `((,boolean? . "boolean")
415     (,char? . "character")
416     (,number? . "number")
417     (,pair? . "pair")
418     (,port? . "port")
419     (,procedure? . "procedure")
420     (,string? . "string")
421     (,symbol? . "symbol")
422     (,vector? . "vector")))
423
424 (define-public r5rs-secondary-predicates
425   `((,char-alphabetic? . "alphabetic character")
426     (,char-lower-case? . "lower-case character")
427     (,char-numeric? . "numeric character")
428     (,char-upper-case? . "upper-case character")
429     (,char-whitespace? . "whitespace character")
430
431     (,complex? . "complex number")
432     (,even? . "even number")
433     (,exact? . "exact number")
434     (,inexact? . "inexact number")
435     (,integer? . "integer")
436     (,negative? . "negative number")
437     (,odd? . "odd number")
438     (,positive? . "positive number")
439     (,rational? . "rational number")
440     (,real? . "real number")
441     (,zero? . "zero")
442
443     (,list? . "list")
444     (,null? . "null")
445
446     (,input-port? . "input port")
447     (,output-port? . "output port")
448
449     ;; would this ever be used?
450     (,eof-object? . "end-of-file object")
451     ))
452
453 (define-public guile-predicates
454   `((,hash-table? . "hash table")
455   ))
456
457 (define-public lilypond-scheme-predicates
458   `((,boolean-or-symbol? . "boolean or symbol")
459     (,color? . "color")
460     (,cheap-list? . "list")
461     (,grob-list? . "list of grobs")
462     ;; this is built on cheap-list
463     (,list-or-symbol? . "list or symbol")
464     (,markup? . "markup")
465     (,markup-command-list? . "markup command list")
466     (,markup-list? . "markup list")
467     (,moment-pair? . "pair of moment objects")
468     (,number-or-grob? . "number or grob")
469     (,number-or-string? . "number or string")
470     (,number-pair? . "pair of numbers")
471     (,rhythmic-location? . "rhythmic location")
472     (,scheme? . "any type")
473     (,string-or-pair? . "string or pair")
474     (,string-or-symbol? . "string or symbol")
475     ))
476
477 (define-public lilypond-exported-predicates
478   `((,ly:box? . "box")
479     (,ly:context? . "context")
480     (,ly:dimension? . "dimension, in staff space")
481     (,ly:dir? . "direction")
482     (,ly:dispatcher? . "dispatcher")
483     (,ly:duration? . "duration")
484     (,ly:font-metric? . "font metric")
485     (,ly:grob? . "graphical (layout) object")
486     (,ly:grob-array? . "array of grobs")
487     (,ly:input-location? . "input location")
488     (,ly:item? . "item")
489     (,ly:iterator? . "iterator")
490     (,ly:lily-lexer? . "lily-lexer")
491     (,ly:lily-parser? . "lily-parser")
492     (,ly:listener? . "listener")
493     (,ly:moment? . "moment")
494     (,ly:music? . "music")
495     (,ly:music-function? . "music function")
496     (,ly:music-list? . "list of music objects")
497     (,ly:music-output? . "music output")
498     (,ly:otf-font? . "OpenType font")
499     (,ly:output-def? . "output definition")
500     (,ly:page-marker? . "page marker")
501     (,ly:pango-font? . "pango font")
502     (,ly:paper-book? . "paper book")
503     (,ly:paper-system? . "paper-system Prob")
504     (,ly:pitch? . "pitch")
505     (,ly:prob? . "property object")
506     (,ly:score? . "score")
507     (,ly:simple-closure? . "simple closure")
508     (,ly:skyline? . "skyline")
509     (,ly:skyline-pair? . "pair of skylines")
510     (,ly:source-file? . "source file")
511     (,ly:spanner? . "spanner")
512     (,ly:stencil? . "stencil")
513     (,ly:stream-event? . "stream event")
514     (,ly:translator? . "translator")
515     (,ly:translator-group? . "translator group")
516     ))
517
518
519 (set! type-p-name-alist
520       (append r5rs-primary-predicates
521               r5rs-secondary-predicates
522               guile-predicates
523               lilypond-scheme-predicates
524               lilypond-exported-predicates))
525
526
527 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
528 ;; timing
529
530 (define (profile-measurements)
531   (let* ((t (times))
532          (stats (gc-stats)))
533     (list (- (+ (tms:cutime t)
534                 (tms:utime t))
535              (assoc-get 'gc-time-taken stats))
536           (assoc-get 'total-cells-allocated  stats 0))))
537
538 (define (dump-profile base last this)
539   (let* ((outname (format "~a.profile" (dir-basename base ".ly")))
540          (diff (map (lambda (y) (apply - y)) (zip this last))))
541     (ly:progress "\nWriting timing to ~a..." outname)
542     (format (open-file outname "w")
543             "time: ~a\ncells: ~a\n"
544             (if (ly:get-option 'dump-cpu-profile)
545                 (car diff)
546                 0)
547             (cadr diff))))
548
549 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
550 ;; debug memory leaks
551
552 (define gc-dumping
553   #f)
554
555 (define gc-protect-stat-count
556   0)
557
558 (define-public (dump-live-object-stats outfile)
559   (for-each (lambda (x)
560               (format outfile "~a: ~a\n" (car x) (cdr x)))
561             (sort (gc-live-object-stats)
562                   (lambda (x y)
563                     (string<? (car x) (car y))))))
564
565 (define-public (dump-gc-protects)
566   (set! gc-protect-stat-count (1+ gc-protect-stat-count))
567   (let* ((protects (sort (hash-table->alist (ly:protects))
568                          (lambda (a b)
569                            (< (object-address (car a))
570                               (object-address (car b))))))
571          (out-file-name (string-append
572                          "gcstat-" (number->string gc-protect-stat-count)
573                          ".scm"))
574          (outfile (open-file out-file-name "w")))
575     (set! gc-dumping #t)
576     (display (format "Dumping GC statistics ~a...\n" out-file-name))
577     (display (map (lambda (y)
578                     (let ((x (car y))
579                           (c (cdr y)))
580                       (display
581                        (format "~a (~a) = ~a\n" (object-address x) c x)
582                        outfile)))
583                   (filter
584                    (lambda (x)
585                      (not (symbol? (car x))))
586                    protects))
587              outfile)
588     (format outfile "\nprotected symbols: ~a\n"
589             (apply + (map (lambda (obj-count)
590                             (if (symbol? (car obj-count))
591                                 (cdr obj-count)
592                                 0))
593                           protects)))
594
595     ;; (display (ly:smob-protects))
596     (newline outfile)
597     (if (defined? 'gc-live-object-stats)
598         (let* ((stats #f))
599           (display "Live object statistics: GC'ing\n")
600           (ly:reset-all-fonts)
601           (gc)
602           (gc)
603           (display "Asserting dead objects\n")
604           (ly:set-option 'debug-gc-assert-parsed-dead #t)
605           (gc)
606           (ly:set-option 'debug-gc-assert-parsed-dead #f)
607           (set! stats (gc-live-object-stats))
608           (display "Dumping live object statistics.\n")
609           (dump-live-object-stats outfile)))
610     (newline outfile)
611     (let* ((stats (gc-stats)))
612       (for-each (lambda (sym)
613                   (display
614                    (format "~a ~a ~a\n"
615                            gc-protect-stat-count
616                            sym
617                            (assoc-get sym stats "?"))
618
619                    outfile))
620                 '(protected-objects bytes-malloced cell-heap-size)))
621     (set! gc-dumping #f)
622     (close-port outfile)))
623
624 (define (check-memory)
625   "Read `/proc/self' to check up on memory use."
626   (define (gulp-file name)
627     (let* ((file (open-input-file name))
628            (text (read-delimited "" file)))
629       (close file)
630       text))
631
632   (let* ((stat (gulp-file "/proc/self/status"))
633          (lines (string-split stat #\newline))
634          (interesting (filter identity
635                               (map
636                                (lambda (l)
637                                  (string-match "^VmData:[ \t]*([0-9]*) kB" l))
638                                lines)))
639          (mem (string->number (match:substring (car interesting) 1))))
640     (display (format  "VMDATA: ~a\n" mem))
641     (display (gc-stats))
642     (if (> mem 100000)
643         (begin (dump-gc-protects)
644                (raise 1)))))
645
646 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
647
648 (define (multi-fork count)
649   "Split this process into COUNT helpers.  Returns either a list of
650 PIDs or the number of the process."
651   (define (helper count acc)
652     (if (> count 0)
653         (let* ((pid (primitive-fork)))
654           (if (= pid 0)
655               (1- count)
656               (helper (1- count) (cons pid acc))))
657         acc))
658
659   (helper count '()))
660
661 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
662
663 (define-public (lilypond-main files)
664   "Entry point for LilyPond."
665   (eval-string (ly:command-line-code))
666   (if (ly:get-option 'help)
667       (begin (ly:option-usage)
668              (exit 0)))
669   (if (ly:get-option 'show-available-fonts)
670       (begin (ly:font-config-display-fonts)
671              (exit 0)))
672   (if (ly:get-option 'gui)
673       (gui-main files))
674   (if (null? files)
675       (begin (ly:usage)
676              (exit 2)))
677   (if (ly:get-option 'read-file-list)
678       (set! files
679             (filter (lambda (s)
680                       (> (string-length s) 0))
681                     (apply append
682                            (map (lambda (f)
683                                   (string-split (ly:gulp-file f) #\nl))
684                                 files)))))
685   (if (and (number? (ly:get-option 'job-count))
686            (>= (length files) (ly:get-option 'job-count)))
687       (let* ((count (ly:get-option 'job-count))
688              (split-todo (split-list files count))
689              (joblist (multi-fork count))
690              (errors '()))
691         (if (not (string-or-symbol? (ly:get-option 'log-file)))
692             (ly:set-option 'log-file "lilypond-multi-run"))
693         (if (number? joblist)
694             (begin (ly:set-option
695                     'log-file (format "~a-~a"
696                                       (ly:get-option 'log-file) joblist))
697                    (set! files (vector-ref split-todo joblist)))
698             (begin (ly:progress "\nForking into jobs:  ~a\n" joblist)
699                    (for-each
700                     (lambda (pid)
701                       (let* ((stat (cdr (waitpid pid))))
702                         (if (not (= stat 0))
703                             (set! errors
704                                   (acons (list-element-index joblist pid)
705                                          stat errors)))))
706                     joblist)
707                    (for-each
708                     (lambda (x)
709                       (let* ((job (car x))
710                              (state (cdr x))
711                              (logfile (format "~a-~a.log"
712                                               (ly:get-option 'log-file) job))
713                              (log (ly:gulp-file logfile))
714                              (len (string-length log))
715                              (tail (substring  log (max 0 (- len 1024)))))
716                         (if (status:term-sig state)
717                             (ly:message
718                              "\n\n~a\n"
719                              (format (_ "job ~a terminated with signal: ~a")
720                                      job (status:term-sig state)))
721                             (ly:message
722                              (_ "logfile ~a (exit ~a):\n~a")
723                              logfile (status:exit-val state) tail))))
724                     errors)
725                    (if (pair? errors)
726                        (ly:error "Children ~a exited with errors."
727                                  (map car errors)))
728                    ;; must overwrite individual entries
729                    (if (ly:get-option 'dump-profile)
730                        (dump-profile "lily-run-total"
731                                      '(0 0) (profile-measurements)))
732                    (exit (if (null? errors)
733                              0
734                              1))))))
735   (if (string-or-symbol? (ly:get-option 'log-file))
736       (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
737   (let ((failed (lilypond-all files)))
738     (if (ly:get-option 'trace-scheme-coverage)
739         (begin
740           (coverage:show-all (lambda (f)
741                                (string-contains f "lilypond")))))
742     (if (pair? failed)
743         (begin (ly:error (_ "failed files: ~S") (string-join failed))
744                (exit 1))
745         (begin
746           ;; HACK: be sure to exit with single newline
747           (ly:message "")
748           (exit 0)))))
749
750 (define-public (lilypond-all files)
751   (let* ((failed '())
752          (separate-logs (ly:get-option 'separate-log-files))
753          (ping-log
754           (if separate-logs
755               (open-file (if (string-or-symbol? (ly:get-option 'log-file))
756                              (format "~a.log" (ly:get-option 'log-file))
757                              "/dev/tty") "a") #f))
758          (do-measurements (ly:get-option 'dump-profile))
759          (handler (lambda (key failed-file)
760                     (set! failed (append (list failed-file) failed)))))
761     (gc)
762     (for-each
763      (lambda (x)
764        (let* ((start-measurements (if do-measurements
765                                       (profile-measurements)
766                                       #f))
767               (base (dir-basename x ".ly"))
768               (all-settings (ly:all-options)))
769          (if separate-logs
770              (ly:stderr-redirect (format "~a.log" base) "w"))
771          (if ping-log
772              (format ping-log "Processing ~a\n" base))
773          (if (ly:get-option 'trace-memory-frequency)
774              (mtrace:start-trace  (ly:get-option 'trace-memory-frequency)))
775          (lilypond-file handler x)
776          (if start-measurements
777              (dump-profile x start-measurements (profile-measurements)))
778          (if (ly:get-option 'trace-memory-frequency)
779              (begin (mtrace:stop-trace)
780                     (mtrace:dump-results base)))
781          (for-each (lambda (s)
782                      (ly:set-option (car s) (cdr s)))
783                    all-settings)
784          (ly:clear-anonymous-modules)
785          (ly:set-option 'debug-gc-assert-parsed-dead #t)
786          (gc)
787          (ly:set-option 'debug-gc-assert-parsed-dead #f)
788          (if (ly:get-option 'debug-gc)
789              (dump-gc-protects)
790              (ly:reset-all-fonts))))
791      files)
792
793     ;; we want the failed-files notice in the aggregrate logfile.
794     (if ping-log
795         (format ping-log "Failed files: ~a\n" failed))
796     (if (ly:get-option 'dump-profile)
797         (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
798     failed))
799
800 (define (lilypond-file handler file-name)
801   (catch 'ly-file-failed
802          (lambda () (ly:parse-file file-name))
803          (lambda (x . args) (handler x file-name))))
804
805 (use-modules (scm editor))
806
807 (define-public (gui-main files)
808   (if (null? files)
809       (gui-no-files-handler))
810   (if (not (string? (ly:get-option 'log-file)))
811       (let* ((base (dir-basename (car files) ".ly"))
812              (log-name (string-append base ".log")))
813         (if (not (ly:get-option 'gui))
814             (ly:message (_ "Redirecting output to ~a...") log-name))
815         (ly:stderr-redirect log-name "w")
816         (ly:message "# -*-compilation-*-"))
817       (let ((failed (lilypond-all files)))
818         (if (pair? failed)
819             (begin
820               ;; ugh
821               (ly:stderr-redirect "foo" "r")
822               (system (get-editor-command log-name 0 0 0))
823               (ly:error (_ "failed files: ~S") (string-join failed))
824               ;; not reached?
825               (exit 1))
826             (exit 0)))))
827
828 (define (gui-no-files-handler)
829   (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
830          ;; FIXME: soft-code, localize
831          (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
832          (cmd (get-editor-command welcome-ly 0 0 0)))
833     (ly:message (_ "Invoking `~a'...\n") cmd)
834     (system cmd)
835     (exit 1)))