]> git.donarmstrong.com Git - lilypond.git/blob - scm/lily.scm
Remove gettext wrappers for ancient Guile versions.
[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 (case PLATFORM
276   ((windows)
277    (define native-getcwd
278      getcwd)
279
280    (define (slashify x)
281      (if (string-index x #\\)
282          x
283          (string-regexp-substitute
284           "//*" "/"
285           (string-regexp-substitute "\\\\" "/" x))))
286
287    ;; FIXME: this prints a warning.
288    (define-public (ly-getcwd)
289      (slashify (native-getcwd))))
290
291   (else
292    (define-public ly-getcwd
293      getcwd)))
294
295 (define-public (is-absolute? file-name)
296   (let ((file-name-length (string-length file-name)))
297     (if (= file-name-length 0)
298         #f
299         (or (eq? (string-ref file-name 0) #\/)
300             (and (eq? PLATFORM 'windows)
301                  (> file-name-length 2)
302                  (eq? (string-ref file-name 1) #\:)
303                  (eq? (string-ref file-name 2) #\/))))))
304
305 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
306
307 (define (type-check-list location signature arguments)
308   "Typecheck a list of arguments against a list of type predicates.
309 Print a message at LOCATION if any predicate failed."
310   (define (recursion-helper signature arguments count)
311     (define (helper pred? arg count)
312       (if (not (pred? arg))
313           (begin
314             (ly:input-message
315              location
316              (format
317               #f (_ "wrong type for argument ~a.  Expecting ~a, found ~s")
318               count (type-name pred?) arg))
319             #f)
320           #t))
321
322     (if (null? signature)
323         #t
324         (and (helper (car signature) (car arguments) count)
325              (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
326   (recursion-helper signature arguments 1))
327
328
329 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
330 ;; Safe definitions utility
331
332 (define safe-objects
333   (list))
334
335 (define-macro (define-safe-public arglist . body)
336   "Define a variable, export it, and mark it as safe, i.e. usable in
337 LilyPond safe mode.  The syntax is the same as `define*-public'."
338   (define (get-symbol arg)
339     (if (pair? arg)
340         (get-symbol (car arg))
341         arg))
342
343   (let ((safe-symbol (get-symbol arglist)))
344     `(begin
345        (define*-public ,arglist
346          ,@body)
347        (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
348                                 safe-objects))
349        ,safe-symbol)))
350
351 (define-safe-public (lilypond-version)
352   (string-join
353    (map (lambda (x) (if (symbol? x)
354                         (symbol->string x)
355                         (number->string x)))
356         (ly:version))
357    "."))
358
359 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
360 ;; init pitch system
361
362 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
363
364 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
365 ;; other files.
366
367 (define init-scheme-files
368   '("lily-library.scm"
369     "file-cache.scm"
370     "define-event-classes.scm"
371     "define-music-types.scm"
372     "output-lib.scm"
373     "c++.scm"
374     "chord-ignatzek-names.scm"
375     "chord-entry.scm"
376     "chord-generic-names.scm"
377     "stencil.scm"
378     "markup.scm"
379     "music-functions.scm"
380     "part-combiner.scm"
381     "autochange.scm"
382     "define-music-properties.scm"
383     "beam-settings.scm"
384     "auto-beam.scm"
385     "chord-name.scm"
386
387     "parser-ly-from-scheme.scm"
388     "ly-syntax-constructors.scm"
389
390     "define-context-properties.scm"
391     "translation-functions.scm"
392     "script.scm"
393     "midi.scm"
394     "layout-beam.scm"
395     "parser-clef.scm"
396     "layout-slur.scm"
397     "font.scm"
398     "encoding.scm"
399
400     "flag-styles.scm"
401     "fret-diagrams.scm"
402     "harp-pedals.scm"
403     "predefined-fretboards.scm"
404     "define-markup-commands.scm"
405     "define-grob-properties.scm"
406     "define-grobs.scm"
407     "define-grob-interfaces.scm"
408     "define-stencil-commands.scm"
409     "titling.scm"
410
411     "paper.scm"
412     "backend-library.scm"
413     "x11-color.scm"
414     "tablature.scm"
415
416     ;; must be after everything has been defined
417     "safe-lily.scm"))
418
419 (for-each ly:load init-scheme-files)
420
421 (set! type-p-name-alist
422       `((,boolean? . "boolean")
423         (,boolean-or-symbol? . "boolean or symbol")
424         (,char? . "char")
425         (,grob-list? . "list of grobs")
426         (,hash-table? . "hash table")
427         (,input-port? . "input port")
428         (,integer? . "integer")
429         (,list? . "list")
430         (,list-or-symbol? . "list or symbol")
431         (,ly:context? . "context")
432         (,ly:dimension? . "dimension, in staff space")
433         (,ly:dir? . "direction")
434         (,ly:duration? . "duration")
435         (,ly:font-metric? . "font metric")
436         (,ly:grob? . "layout object")
437         (,ly:grob-array? . "array of grobs")
438         (,ly:input-location? . "input location")
439         (,ly:moment? . "moment")
440         (,ly:music? . "music")
441         (,ly:music-list? . "list of music objects")
442         (,ly:music-output? . "music output")
443         (,ly:pitch? . "pitch")
444         (,ly:translator? . "translator")
445         (,ly:score? . "score")
446         (,ly:simple-closure? . "simple closure")
447         (,ly:skyline-pair? . "pair of skylines")
448         (,ly:stencil? . "stencil")
449         (,markup-list? . "list of markups")
450         (,markup? . "markup")
451         (,number-or-grob? . "number or grob")
452         (,number-or-string? . "number or string")
453         (,number-pair? . "pair of numbers")
454         (,number? . "number")
455         (,output-port? . "output port")
456         (,pair? . "pair")
457         (,procedure? . "procedure")
458         (,real? . "real number")
459         (,rhythmic-location? . "rhythmic location")
460         (,scheme? . "any type")
461         (,string? . "string")
462         (,string-or-pair? . "string or pair")
463         (,symbol? . "symbol")
464         (,vector? . "vector")))
465
466 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
467 ;; timing
468
469 (define (profile-measurements)
470   (let* ((t (times))
471          (stats (gc-stats)))
472     (list (- (+ (tms:cutime t)
473                 (tms:utime t))
474              (assoc-get 'gc-time-taken stats))
475           (assoc-get 'total-cells-allocated  stats 0))))
476
477 (define (dump-profile base last this)
478   (let* ((outname (format "~a.profile" (dir-basename base ".ly")))
479          (diff (map (lambda (y) (apply - y)) (zip this last))))
480     (ly:progress "\nWriting timing to ~a..." outname)
481     (format (open-file outname "w")
482             "time: ~a\ncells: ~a\n"
483             (if (ly:get-option 'dump-cpu-profile)
484                 (car diff)
485                 0)
486             (cadr diff))))
487
488 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
489 ;; debug memory leaks
490
491 (define gc-dumping
492   #f)
493
494 (define gc-protect-stat-count
495   0)
496
497 (define-public (dump-live-object-stats outfile)
498   (for-each (lambda (x)
499               (format outfile "~a: ~a\n" (car x) (cdr x)))
500             (sort (gc-live-object-stats)
501                   (lambda (x y)
502                     (string<? (car x) (car y))))))
503
504 (define-public (dump-gc-protects)
505   (set! gc-protect-stat-count (1+ gc-protect-stat-count))
506   (let* ((protects (sort (hash-table->alist (ly:protects))
507                          (lambda (a b)
508                            (< (object-address (car a))
509                               (object-address (car b))))))
510          (out-file-name (string-append
511                          "gcstat-" (number->string gc-protect-stat-count)
512                          ".scm"))
513          (outfile (open-file out-file-name "w")))
514     (set! gc-dumping #t)
515     (display (format "Dumping GC statistics ~a...\n" out-file-name))
516     (display (map (lambda (y)
517                     (let ((x (car y))
518                           (c (cdr y)))
519                       (display
520                        (format "~a (~a) = ~a\n" (object-address x) c x)
521                        outfile)))
522                   (filter
523                    (lambda (x)
524                      (not (symbol? (car x))))
525                    protects))
526              outfile)
527     (format outfile "\nprotected symbols: ~a\n"
528             (apply + (map (lambda (obj-count)
529                             (if (symbol? (car obj-count))
530                                 (cdr obj-count)
531                                 0))
532                           protects)))
533
534     ;; (display (ly:smob-protects))
535     (newline outfile)
536     (if (defined? 'gc-live-object-stats)
537         (let* ((stats #f))
538           (display "Live object statistics: GC'ing\n")
539           (ly:reset-all-fonts)
540           (gc)
541           (gc)
542           (display "Asserting dead objects\n")
543           (ly:set-option 'debug-gc-assert-parsed-dead #t)
544           (gc)
545           (ly:set-option 'debug-gc-assert-parsed-dead #f)
546           (set! stats (gc-live-object-stats))
547           (display "Dumping live object statistics.\n")
548           (dump-live-object-stats outfile)))
549     (newline outfile)
550     (let* ((stats (gc-stats)))
551       (for-each (lambda (sym)
552                   (display
553                    (format "~a ~a ~a\n"
554                            gc-protect-stat-count
555                            sym
556                            (assoc-get sym stats "?"))
557
558                    outfile))
559                 '(protected-objects bytes-malloced cell-heap-size)))
560     (set! gc-dumping #f)
561     (close-port outfile)))
562
563 (define (check-memory)
564   "Read `/proc/self' to check up on memory use."
565   (define (gulp-file name)
566     (let* ((file (open-input-file name))
567            (text (read-delimited "" file)))
568       (close file)
569       text))
570
571   (let* ((stat (gulp-file "/proc/self/status"))
572          (lines (string-split stat #\newline))
573          (interesting (filter identity
574                               (map
575                                (lambda (l)
576                                  (string-match "^VmData:[ \t]*([0-9]*) kB" l))
577                                lines)))
578          (mem (string->number (match:substring (car interesting) 1))))
579     (display (format  "VMDATA: ~a\n" mem))
580     (display (gc-stats))
581     (if (> mem 100000)
582         (begin (dump-gc-protects)
583                (raise 1)))))
584
585 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
586
587 (define (multi-fork count)
588   "Split this process into COUNT helpers.  Returns either a list of
589 PIDs or the number of the process."
590   (define (helper count acc)
591     (if (> count 0)
592         (let* ((pid (primitive-fork)))
593           (if (= pid 0)
594               (1- count)
595               (helper (1- count) (cons pid acc))))
596         acc))
597
598   (helper count '()))
599
600 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
601
602 (define-public (lilypond-main files)
603   "Entry point for LilyPond."
604   (eval-string (ly:command-line-code))
605   (if (ly:get-option 'help)
606       (begin (ly:option-usage)
607              (exit 0)))
608   (if (ly:get-option 'show-available-fonts)
609       (begin (ly:font-config-display-fonts)
610              (exit 0)))
611   (if (ly:get-option 'gui)
612       (gui-main files))
613   (if (null? files)
614       (begin (ly:usage)
615              (exit 2)))
616   (if (ly:get-option 'read-file-list)
617       (set! files
618             (filter (lambda (s)
619                       (> (string-length s) 0))
620                     (apply append
621                            (map (lambda (f)
622                                   (string-split (ly:gulp-file f) #\nl))
623                                 files)))))
624   (if (and (number? (ly:get-option 'job-count))
625            (>= (length files) (ly:get-option 'job-count)))
626       (let* ((count (ly:get-option 'job-count))
627              (split-todo (split-list files count))
628              (joblist (multi-fork count))
629              (errors '()))
630         (if (not (string-or-symbol? (ly:get-option 'log-file)))
631             (ly:set-option 'log-file "lilypond-multi-run"))
632         (if (number? joblist)
633             (begin (ly:set-option
634                     'log-file (format "~a-~a"
635                                       (ly:get-option 'log-file) joblist))
636                    (set! files (vector-ref split-todo joblist)))
637             (begin (ly:progress "\nForking into jobs:  ~a\n" joblist)
638                    (for-each
639                     (lambda (pid)
640                       (let* ((stat (cdr (waitpid pid))))
641                         (if (not (= stat 0))
642                             (set! errors
643                                   (acons (list-element-index joblist pid)
644                                          stat errors)))))
645                     joblist)
646                    (for-each
647                     (lambda (x)
648                       (let* ((job (car x))
649                              (state (cdr x))
650                              (logfile (format "~a-~a.log"
651                                               (ly:get-option 'log-file) job))
652                              (log (ly:gulp-file logfile))
653                              (len (string-length log))
654                              (tail (substring  log (max 0 (- len 1024)))))
655                         (if (status:term-sig state)
656                             (ly:message
657                              "\n\n~a\n"
658                              (format (_ "job ~a terminated with signal: ~a")
659                                      job (status:term-sig state)))
660                             (ly:message
661                              (_ "logfile ~a (exit ~a):\n~a")
662                              logfile (status:exit-val state) tail))))
663                     errors)
664                    (if (pair? errors)
665                        (ly:error "Children ~a exited with errors."
666                                  (map car errors)))
667                    ;; must overwrite individual entries
668                    (if (ly:get-option 'dump-profile)
669                        (dump-profile "lily-run-total"
670                                      '(0 0) (profile-measurements)))
671                    (exit (if (null? errors)
672                              0
673                              1))))))
674   (if (string-or-symbol? (ly:get-option 'log-file))
675       (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
676   (let ((failed (lilypond-all files)))
677     (if (ly:get-option 'trace-scheme-coverage)
678         (begin
679           (coverage:show-all (lambda (f)
680                                (string-contains f "lilypond")))))
681     (if (pair? failed)
682         (begin (ly:error (_ "failed files: ~S") (string-join failed))
683                (exit 1))
684         (begin
685           ;; HACK: be sure to exit with single newline
686           (ly:message "")
687           (exit 0)))))
688
689 (define-public (lilypond-all files)
690   (let* ((failed '())
691          (separate-logs (ly:get-option 'separate-log-files))
692          (ping-log
693           (if separate-logs
694               (open-file (if (string-or-symbol? (ly:get-option 'log-file))
695                              (format "~a.log" (ly:get-option 'log-file))
696                              "/dev/tty") "a") #f))
697          (do-measurements (ly:get-option 'dump-profile))
698          (handler (lambda (key failed-file)
699                     (set! failed (append (list failed-file) failed)))))
700     (gc)
701     (for-each
702      (lambda (x)
703        (let* ((start-measurements (if do-measurements
704                                       (profile-measurements)
705                                       #f))
706               (base (dir-basename x ".ly"))
707               (all-settings (ly:all-options)))
708          (if separate-logs
709              (ly:stderr-redirect (format "~a.log" base) "w"))
710          (if ping-log
711              (format ping-log "Processing ~a\n" base))
712          (if (ly:get-option 'trace-memory-frequency)
713              (mtrace:start-trace  (ly:get-option 'trace-memory-frequency)))
714          (lilypond-file handler x)
715          (if start-measurements
716              (dump-profile x start-measurements (profile-measurements)))
717          (if (ly:get-option 'trace-memory-frequency)
718              (begin (mtrace:stop-trace)
719                     (mtrace:dump-results base)))
720          (for-each (lambda (s)
721                      (ly:set-option (car s) (cdr s)))
722                    all-settings)
723          (ly:clear-anonymous-modules)
724          (ly:set-option 'debug-gc-assert-parsed-dead #t)
725          (gc)
726          (ly:set-option 'debug-gc-assert-parsed-dead #f)
727          (if (ly:get-option 'debug-gc)
728              (dump-gc-protects)
729              (if (= (random 40) 1)
730                  (ly:reset-all-fonts)))))
731      files)
732
733     ;; we want the failed-files notice in the aggregrate logfile.
734     (if ping-log
735         (format ping-log "Failed files: ~a\n" failed))
736     (if (ly:get-option 'dump-profile)
737         (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
738     failed))
739
740 (define (lilypond-file handler file-name)
741   (catch 'ly-file-failed
742          (lambda () (ly:parse-file file-name))
743          (lambda (x . args) (handler x file-name))))
744
745 (use-modules (scm editor))
746
747 (define-public (gui-main files)
748   (if (null? files)
749       (gui-no-files-handler))
750   (if (not (string? (ly:get-option 'log-file)))
751       (let* ((base (dir-basename (car files) ".ly"))
752              (log-name (string-append base ".log")))
753         (if (not (ly:get-option 'gui))
754             (ly:message (_ "Redirecting output to ~a...") log-name))
755         (ly:stderr-redirect log-name "w")
756         (ly:message "# -*-compilation-*-"))
757       (let ((failed (lilypond-all files)))
758         (if (pair? failed)
759             (begin
760               ;; ugh
761               (ly:stderr-redirect "foo" "r")
762               (system (get-editor-command log-name 0 0 0))
763               (ly:error (_ "failed files: ~S") (string-join failed))
764               ;; not reached?
765               (exit 1))
766             (exit 0)))))
767
768 (define (gui-no-files-handler)
769   (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
770          ;; FIXME: soft-code, localize
771          (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
772          (cmd (get-editor-command welcome-ly 0 0 0)))
773     (ly:message (_ "Invoking `~a'...\n") cmd)
774     (system cmd)
775     (exit 1)))