]> git.donarmstrong.com Git - lilypond.git/blob - scm/lily.scm
Update source file headers. Fixes using standard GNU package conventions.
[lilypond.git] / scm / lily.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 1998--2009 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     (old-relative #f
119 "Make \\relative mode for simultaneous music work
120 similar to chord syntax.")
121     (point-and-click #t
122 "Add point & click links to PDF output.")
123     (paper-size "a4"
124 "Set default paper size.")
125     (pixmap-format "png16m"
126 "Set GhostScript's output format for pixel images.")
127     (preview #f
128 "Create PNG and EPS preview images also.")
129     (print-pages #t
130 "Print pages in the normal way.")
131     (protected-scheme-parsing #t
132 "Continue when errors in inline scheme are caught
133 in the parser.  If #f, halt on errors and print
134 a stack trace.")
135     (profile-property-accesses #f
136 "Keep statistics of get_property() calls.")
137     (resolution 101
138 "Set resolution for generating PNG pixmaps to
139 given value (in dpi).")
140     (read-file-list #f
141 "Specify name of a file which contains a list of
142 input files to be processed.")
143     (relative-includes #f
144 "When processing an \\include command, look for
145 the included file relative to the current file
146 (instead of the root file)")
147     (safe #f
148 "Run in safer mode.")
149     (strict-infinity-checking #f
150 "Force a crash on encountering Inf and NaN
151 floating point exceptions.")
152     (strip-output-dir #t
153 "Don't use directories from input files while
154 constructing output file names.")
155     (separate-log-files #f
156 "For input files `FILE1.ly', `FILE2.ly', ...
157 output log data to files `FILE1.log',
158 `FILE2.log', ...")
159     (trace-memory-frequency #f
160 "Record Scheme cell usage this many times per
161 second.  Dump results to `FILE.stacks' and
162 `FILE.graph'.")
163     (trace-scheme-coverage #f
164 "Record coverage of Scheme files in `FILE.cov'.")
165     (show-available-fonts #f
166 "List available font names.")
167     (verbose ,(ly:command-line-verbose?)
168 "Value of the --verbose flag (read-only).")
169     (warning-as-error #f
170 "Change all warning and programming_error
171 messages into errors.")
172     ))
173
174 ;; Need to do this in the beginning.  Other parts of the Scheme
175 ;; initialization depend on these options.
176
177 (for-each (lambda (x)
178             (ly:add-option (car x) (cadr x) (caddr x)))
179           scheme-options-definitions)
180
181 (for-each (lambda (x)
182             (ly:set-option (car x) (cdr x)))
183           (eval-string (ly:command-line-options)))
184
185 (debug-set! stack 0)
186
187 (if (defined? 'set-debug-cell-accesses!)
188     (set-debug-cell-accesses! #f))
189
190                                         ;(set-debug-cell-accesses! 1000)
191
192 (use-modules (ice-9 regex)
193              (ice-9 safe)
194              (ice-9 format)
195              (ice-9 rdelim)
196              (ice-9 optargs)
197              (oop goops)
198              (srfi srfi-1)
199              (srfi srfi-13)
200              (srfi srfi-14)
201              (scm clip-region)
202              (scm memory-trace)
203              (scm coverage))
204
205 (define-public fancy-format
206   format)
207
208 (define-public (ergonomic-simple-format dest . rest)
209   "Like ice-9 format, but without the memory consumption."
210   (if (string? dest)
211       (apply simple-format (cons #f (cons dest rest)))
212       (apply simple-format (cons dest rest))))
213
214 (define format
215   ergonomic-simple-format)
216
217 ;; my display
218 (define-public (myd k v)
219   (display k)
220   (display ": ")
221   (display v)
222   (display ", ")
223   v)
224
225 (define-public (print . args)
226   (apply format (cons (current-output-port) args)))
227
228
229 ;;; General settings.
230 ;;;
231 ;;; Debugging evaluator is slower.  This should have a more sensible
232 ;;; default.
233
234 (if (or (ly:get-option 'verbose)
235         (ly:get-option 'trace-memory-frequency)
236         (ly:get-option 'trace-scheme-coverage))
237     (begin
238       (ly:set-option 'protected-scheme-parsing #f)
239       (debug-enable 'debug)
240       (debug-enable 'backtrace)
241       (read-enable 'positions)))
242
243 (if (ly:get-option 'trace-scheme-coverage)
244     (coverage:enable))
245
246 (define-public parser #f)
247
248
249 ;; gettext wrapper for guile < 1.7.2
250 (if (defined? 'gettext)
251     (define-public _ gettext)
252     (define-public _ ly:gettext))
253
254 (define-public (ly:load x)
255   (let* ((file-name (%search-load-path x)))
256     (if (ly:get-option 'verbose)
257         (ly:progress "[~A" file-name))
258     (if (not file-name)
259         (ly:error (_ "cannot find: ~A") x))
260     (primitive-load file-name)
261     (if (ly:get-option 'verbose)
262         (ly:progress "]\n"))))
263
264 (define-public DOS
265   (let ((platform (string-tokenize
266                    (vector-ref (uname) 0) char-set:letter+digit)))
267     (if (null? (cdr platform)) #f
268         (member (string-downcase (cadr platform)) '("95" "98" "me")))))
269
270 (case PLATFORM
271   ((windows)
272    (define native-getcwd
273      getcwd)
274
275    (define (slashify x)
276      (if (string-index x #\\)
277          x
278          (string-regexp-substitute
279           "//*" "/"
280           (string-regexp-substitute "\\\\" "/" x))))
281
282    ;; FIXME: this prints a warning.
283    (define-public (ly-getcwd)
284      (slashify (native-getcwd))))
285
286   (else
287    (define-public ly-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
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     "predefined-fretboards.scm"
399     "define-markup-commands.scm"
400     "define-grob-properties.scm"
401     "define-grobs.scm"
402     "define-grob-interfaces.scm"
403     "define-stencil-commands.scm"
404     "titling.scm"
405
406     "paper.scm"
407     "backend-library.scm"
408     "x11-color.scm"
409     "tablature.scm"
410
411     ;; must be after everything has been defined
412     "safe-lily.scm"))
413
414 (for-each ly:load init-scheme-files)
415
416 (set! type-p-name-alist
417       `((,boolean? . "boolean")
418         (,boolean-or-symbol? . "boolean or symbol")
419         (,char? . "char")
420         (,grob-list? . "list of grobs")
421         (,hash-table? . "hash table")
422         (,input-port? . "input port")
423         (,integer? . "integer")
424         (,list? . "list")
425         (,ly:context? . "context")
426         (,ly:dimension? . "dimension, in staff space")
427         (,ly:dir? . "direction")
428         (,ly:duration? . "duration")
429         (,ly:font-metric? . "font metric")
430         (,ly:grob? . "layout object")
431         (,ly:grob-array? . "array of grobs")
432         (,ly:input-location? . "input location")
433         (,ly:moment? . "moment")
434         (,ly:music? . "music")
435         (,ly:music-list? . "list of music objects")
436         (,ly:music-output? . "music output")
437         (,ly:pitch? . "pitch")
438         (,ly:translator? . "translator")
439         (,ly:score? . "score")
440         (,ly:simple-closure? . "simple closure")
441         (,ly:skyline-pair? . "pair of skylines")
442         (,ly:stencil? . "stencil")
443         (,markup-list? . "list of markups")
444         (,markup? . "markup")
445         (,number-or-grob? . "number or grob")
446         (,number-or-string? . "number or string")
447         (,number-pair? . "pair of numbers")
448         (,number? . "number")
449         (,output-port? . "output port")
450         (,pair? . "pair")
451         (,procedure? . "procedure")
452         (,rhythmic-location? . "rhythmic location")
453         (,scheme? . "any type")
454         (,string? . "string")
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              (if (= (random 40) 1)
722                  (ly:reset-all-fonts)))))
723      files)
724
725     ;; we want the failed-files notice in the aggregrate logfile.
726     (if ping-log
727         (format ping-log "Failed files: ~a\n" failed))
728     (if (ly:get-option 'dump-profile)
729         (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
730     failed))
731
732 (define (lilypond-file handler file-name)
733   (catch 'ly-file-failed
734          (lambda () (ly:parse-file file-name))
735          (lambda (x . args) (handler x file-name))))
736
737 (use-modules (scm editor))
738
739 (define-public (gui-main files)
740   (if (null? files)
741       (gui-no-files-handler))
742   (if (not (string? (ly:get-option 'log-file)))
743       (let* ((base (dir-basename (car files) ".ly"))
744              (log-name (string-append base ".log")))
745         (if (not (ly:get-option 'gui))
746             (ly:message (_ "Redirecting output to ~a...") log-name))
747         (ly:stderr-redirect log-name "w")
748         (ly:message "# -*-compilation-*-"))
749       (let ((failed (lilypond-all files)))
750         (if (pair? failed)
751             (begin
752               ;; ugh
753               (ly:stderr-redirect "foo" "r")
754               (system (get-editor-command log-name 0 0 0))
755               (ly:error (_ "failed files: ~S") (string-join failed))
756               ;; not reached?
757               (exit 1))
758             (exit 0)))))
759
760 (define (gui-no-files-handler)
761   (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
762          ;; FIXME: soft-code, localize
763          (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
764          (cmd (get-editor-command welcome-ly 0 0 0)))
765     (ly:message (_ "Invoking `~a'...\n") cmd)
766     (system cmd)
767     (exit 1)))