]> git.donarmstrong.com Git - lilypond.git/blob - scm/lily.scm
8cfebbd0db26366f405b8f93712f82470eefbd52
[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 (set! type-p-name-alist
414       `((,boolean? . "boolean")
415         (,boolean-or-symbol? . "boolean or symbol")
416         (,char? . "char")
417         (,grob-list? . "list of grobs")
418         (,hash-table? . "hash table")
419         (,input-port? . "input port")
420         (,integer? . "integer")
421         (,list? . "list")
422         (,list-or-symbol? . "list or symbol")
423         (,ly:context? . "context")
424         (,ly:dimension? . "dimension, in staff space")
425         (,ly:dir? . "direction")
426         (,ly:duration? . "duration")
427         (,ly:font-metric? . "font metric")
428         (,ly:grob? . "layout object")
429         (,ly:grob-array? . "array of grobs")
430         (,ly:input-location? . "input location")
431         (,ly:moment? . "moment")
432         (,ly:music? . "music")
433         (,ly:music-list? . "list of music objects")
434         (,ly:music-output? . "music output")
435         (,ly:pitch? . "pitch")
436         (,ly:translator? . "translator")
437         (,ly:score? . "score")
438         (,ly:simple-closure? . "simple closure")
439         (,ly:skyline-pair? . "pair of skylines")
440         (,ly:stencil? . "stencil")
441         (,markup-list? . "list of markups")
442         (,markup? . "markup")
443         (,number-or-grob? . "number or grob")
444         (,number-or-string? . "number or string")
445         (,number-pair? . "pair of numbers")
446         (,number? . "number")
447         (,output-port? . "output port")
448         (,pair? . "pair")
449         (,procedure? . "procedure")
450         (,real? . "real number")
451         (,rhythmic-location? . "rhythmic location")
452         (,scheme? . "any type")
453         (,string? . "string")
454         (,string-or-pair? . "string or pair")
455         (,symbol? . "symbol")
456         (,vector? . "vector")))
457
458 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
459 ;; timing
460
461 (define (profile-measurements)
462   (let* ((t (times))
463          (stats (gc-stats)))
464     (list (- (+ (tms:cutime t)
465                 (tms:utime t))
466              (assoc-get 'gc-time-taken stats))
467           (assoc-get 'total-cells-allocated  stats 0))))
468
469 (define (dump-profile base last this)
470   (let* ((outname (format "~a.profile" (dir-basename base ".ly")))
471          (diff (map (lambda (y) (apply - y)) (zip this last))))
472     (ly:progress "\nWriting timing to ~a..." outname)
473     (format (open-file outname "w")
474             "time: ~a\ncells: ~a\n"
475             (if (ly:get-option 'dump-cpu-profile)
476                 (car diff)
477                 0)
478             (cadr diff))))
479
480 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
481 ;; debug memory leaks
482
483 (define gc-dumping
484   #f)
485
486 (define gc-protect-stat-count
487   0)
488
489 (define-public (dump-live-object-stats outfile)
490   (for-each (lambda (x)
491               (format outfile "~a: ~a\n" (car x) (cdr x)))
492             (sort (gc-live-object-stats)
493                   (lambda (x y)
494                     (string<? (car x) (car y))))))
495
496 (define-public (dump-gc-protects)
497   (set! gc-protect-stat-count (1+ gc-protect-stat-count))
498   (let* ((protects (sort (hash-table->alist (ly:protects))
499                          (lambda (a b)
500                            (< (object-address (car a))
501                               (object-address (car b))))))
502          (out-file-name (string-append
503                          "gcstat-" (number->string gc-protect-stat-count)
504                          ".scm"))
505          (outfile (open-file out-file-name "w")))
506     (set! gc-dumping #t)
507     (display (format "Dumping GC statistics ~a...\n" out-file-name))
508     (display (map (lambda (y)
509                     (let ((x (car y))
510                           (c (cdr y)))
511                       (display
512                        (format "~a (~a) = ~a\n" (object-address x) c x)
513                        outfile)))
514                   (filter
515                    (lambda (x)
516                      (not (symbol? (car x))))
517                    protects))
518              outfile)
519     (format outfile "\nprotected symbols: ~a\n"
520             (apply + (map (lambda (obj-count)
521                             (if (symbol? (car obj-count))
522                                 (cdr obj-count)
523                                 0))
524                           protects)))
525
526     ;; (display (ly:smob-protects))
527     (newline outfile)
528     (if (defined? 'gc-live-object-stats)
529         (let* ((stats #f))
530           (display "Live object statistics: GC'ing\n")
531           (ly:reset-all-fonts)
532           (gc)
533           (gc)
534           (display "Asserting dead objects\n")
535           (ly:set-option 'debug-gc-assert-parsed-dead #t)
536           (gc)
537           (ly:set-option 'debug-gc-assert-parsed-dead #f)
538           (set! stats (gc-live-object-stats))
539           (display "Dumping live object statistics.\n")
540           (dump-live-object-stats outfile)))
541     (newline outfile)
542     (let* ((stats (gc-stats)))
543       (for-each (lambda (sym)
544                   (display
545                    (format "~a ~a ~a\n"
546                            gc-protect-stat-count
547                            sym
548                            (assoc-get sym stats "?"))
549
550                    outfile))
551                 '(protected-objects bytes-malloced cell-heap-size)))
552     (set! gc-dumping #f)
553     (close-port outfile)))
554
555 (define (check-memory)
556   "Read `/proc/self' to check up on memory use."
557   (define (gulp-file name)
558     (let* ((file (open-input-file name))
559            (text (read-delimited "" file)))
560       (close file)
561       text))
562
563   (let* ((stat (gulp-file "/proc/self/status"))
564          (lines (string-split stat #\newline))
565          (interesting (filter identity
566                               (map
567                                (lambda (l)
568                                  (string-match "^VmData:[ \t]*([0-9]*) kB" l))
569                                lines)))
570          (mem (string->number (match:substring (car interesting) 1))))
571     (display (format  "VMDATA: ~a\n" mem))
572     (display (gc-stats))
573     (if (> mem 100000)
574         (begin (dump-gc-protects)
575                (raise 1)))))
576
577 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
578
579 (define (multi-fork count)
580   "Split this process into COUNT helpers.  Returns either a list of
581 PIDs or the number of the process."
582   (define (helper count acc)
583     (if (> count 0)
584         (let* ((pid (primitive-fork)))
585           (if (= pid 0)
586               (1- count)
587               (helper (1- count) (cons pid acc))))
588         acc))
589
590   (helper count '()))
591
592 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
593
594 (define-public (lilypond-main files)
595   "Entry point for LilyPond."
596   (eval-string (ly:command-line-code))
597   (if (ly:get-option 'help)
598       (begin (ly:option-usage)
599              (exit 0)))
600   (if (ly:get-option 'show-available-fonts)
601       (begin (ly:font-config-display-fonts)
602              (exit 0)))
603   (if (ly:get-option 'gui)
604       (gui-main files))
605   (if (null? files)
606       (begin (ly:usage)
607              (exit 2)))
608   (if (ly:get-option 'read-file-list)
609       (set! files
610             (filter (lambda (s)
611                       (> (string-length s) 0))
612                     (apply append
613                            (map (lambda (f)
614                                   (string-split (ly:gulp-file f) #\nl))
615                                 files)))))
616   (if (and (number? (ly:get-option 'job-count))
617            (>= (length files) (ly:get-option 'job-count)))
618       (let* ((count (ly:get-option 'job-count))
619              (split-todo (split-list files count))
620              (joblist (multi-fork count))
621              (errors '()))
622         (if (not (string-or-symbol? (ly:get-option 'log-file)))
623             (ly:set-option 'log-file "lilypond-multi-run"))
624         (if (number? joblist)
625             (begin (ly:set-option
626                     'log-file (format "~a-~a"
627                                       (ly:get-option 'log-file) joblist))
628                    (set! files (vector-ref split-todo joblist)))
629             (begin (ly:progress "\nForking into jobs:  ~a\n" joblist)
630                    (for-each
631                     (lambda (pid)
632                       (let* ((stat (cdr (waitpid pid))))
633                         (if (not (= stat 0))
634                             (set! errors
635                                   (acons (list-element-index joblist pid)
636                                          stat errors)))))
637                     joblist)
638                    (for-each
639                     (lambda (x)
640                       (let* ((job (car x))
641                              (state (cdr x))
642                              (logfile (format "~a-~a.log"
643                                               (ly:get-option 'log-file) job))
644                              (log (ly:gulp-file logfile))
645                              (len (string-length log))
646                              (tail (substring  log (max 0 (- len 1024)))))
647                         (if (status:term-sig state)
648                             (ly:message
649                              "\n\n~a\n"
650                              (format (_ "job ~a terminated with signal: ~a")
651                                      job (status:term-sig state)))
652                             (ly:message
653                              (_ "logfile ~a (exit ~a):\n~a")
654                              logfile (status:exit-val state) tail))))
655                     errors)
656                    (if (pair? errors)
657                        (ly:error "Children ~a exited with errors."
658                                  (map car errors)))
659                    ;; must overwrite individual entries
660                    (if (ly:get-option 'dump-profile)
661                        (dump-profile "lily-run-total"
662                                      '(0 0) (profile-measurements)))
663                    (exit (if (null? errors)
664                              0
665                              1))))))
666   (if (string-or-symbol? (ly:get-option 'log-file))
667       (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
668   (let ((failed (lilypond-all files)))
669     (if (ly:get-option 'trace-scheme-coverage)
670         (begin
671           (coverage:show-all (lambda (f)
672                                (string-contains f "lilypond")))))
673     (if (pair? failed)
674         (begin (ly:error (_ "failed files: ~S") (string-join failed))
675                (exit 1))
676         (begin
677           ;; HACK: be sure to exit with single newline
678           (ly:message "")
679           (exit 0)))))
680
681 (define-public (lilypond-all files)
682   (let* ((failed '())
683          (separate-logs (ly:get-option 'separate-log-files))
684          (ping-log
685           (if separate-logs
686               (open-file (if (string-or-symbol? (ly:get-option 'log-file))
687                              (format "~a.log" (ly:get-option 'log-file))
688                              "/dev/tty") "a") #f))
689          (do-measurements (ly:get-option 'dump-profile))
690          (handler (lambda (key failed-file)
691                     (set! failed (append (list failed-file) failed)))))
692     (gc)
693     (for-each
694      (lambda (x)
695        (let* ((start-measurements (if do-measurements
696                                       (profile-measurements)
697                                       #f))
698               (base (dir-basename x ".ly"))
699               (all-settings (ly:all-options)))
700          (if separate-logs
701              (ly:stderr-redirect (format "~a.log" base) "w"))
702          (if ping-log
703              (format ping-log "Processing ~a\n" base))
704          (if (ly:get-option 'trace-memory-frequency)
705              (mtrace:start-trace  (ly:get-option 'trace-memory-frequency)))
706          (lilypond-file handler x)
707          (if start-measurements
708              (dump-profile x start-measurements (profile-measurements)))
709          (if (ly:get-option 'trace-memory-frequency)
710              (begin (mtrace:stop-trace)
711                     (mtrace:dump-results base)))
712          (for-each (lambda (s)
713                      (ly:set-option (car s) (cdr s)))
714                    all-settings)
715          (ly:clear-anonymous-modules)
716          (ly:set-option 'debug-gc-assert-parsed-dead #t)
717          (gc)
718          (ly:set-option 'debug-gc-assert-parsed-dead #f)
719          (if (ly:get-option 'debug-gc)
720              (dump-gc-protects)
721              (ly:reset-all-fonts))))
722      files)
723
724     ;; we want the failed-files notice in the aggregrate logfile.
725     (if ping-log
726         (format ping-log "Failed files: ~a\n" failed))
727     (if (ly:get-option 'dump-profile)
728         (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
729     failed))
730
731 (define (lilypond-file handler file-name)
732   (catch 'ly-file-failed
733          (lambda () (ly:parse-file file-name))
734          (lambda (x . args) (handler x file-name))))
735
736 (use-modules (scm editor))
737
738 (define-public (gui-main files)
739   (if (null? files)
740       (gui-no-files-handler))
741   (if (not (string? (ly:get-option 'log-file)))
742       (let* ((base (dir-basename (car files) ".ly"))
743              (log-name (string-append base ".log")))
744         (if (not (ly:get-option 'gui))
745             (ly:message (_ "Redirecting output to ~a...") log-name))
746         (ly:stderr-redirect log-name "w")
747         (ly:message "# -*-compilation-*-"))
748       (let ((failed (lilypond-all files)))
749         (if (pair? failed)
750             (begin
751               ;; ugh
752               (ly:stderr-redirect "foo" "r")
753               (system (get-editor-command log-name 0 0 0))
754               (ly:error (_ "failed files: ~S") (string-join failed))
755               ;; not reached?
756               (exit 1))
757             (exit 0)))))
758
759 (define (gui-no-files-handler)
760   (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
761          ;; FIXME: soft-code, localize
762          (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
763          (cmd (get-editor-command welcome-ly 0 0 0)))
764     (ly:message (_ "Invoking `~a'...\n") cmd)
765     (system cmd)
766     (exit 1)))