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