]> git.donarmstrong.com Git - lilypond.git/blob - scm/lily.scm
Merge branch 'master' of ssh://jomand@git.sv.gnu.org/srv/git/lilypond
[lilypond.git] / scm / lily.scm
1 ;;;; lily.scm -- top-level Scheme stuff
2 ;;;;
3 ;;;;  source file of the GNU LilyPond music typesetter
4 ;;;;
5 ;;;; (c) 1998--2009 Jan Nieuwenhuizen <janneke@gnu.org>
6 ;;;; Han-Wen Nienhuys <hanwen@xs4all.nl>
7
8 ;; Internationalisation: (_i "to be translated") gets an entry in the
9 ;; POT file; (gettext ...) must be invoked explicitly to do the actual
10 ;; "translation".
11 ;;
12 ;; (define-macro (_i x) x)
13 ;; (define-macro-public _i (x) x)
14 ;; (define-public-macro _i (x) x)
15 ;; Abbrv-PWR!
16
17 (defmacro-public _i (x) x)
18
19 (read-enable 'positions)
20 (debug-enable 'debug)
21
22 (define-public PLATFORM
23   (string->symbol
24    (string-downcase
25     (car (string-tokenize (utsname:sysname (uname)))))))
26
27 (define scheme-options-definitions
28   `(
29     ;; NAMING: either
30
31     ;; - [subject-]object-object-verb +"ing"
32     ;; - [subject-]-verb-object-object
33
34     ;; Avoid overlong lines in `lilypond -dhelp'!  Strings should not
35     ;; be longer than 48 characters per line.
36
37     (anti-alias-factor 1
38 "Render at higher resolution (using given factor)
39 and scale down result to prevent jaggies in
40 PNG images.")
41     (backend ps
42 "Select backend.  Possible values: 'eps, 'null,
43 'ps, 'scm, 'socket, 'svg.")
44     (check-internal-types #f
45 "Check every property assignment for types.")
46     (clip-systems #f
47 "Generate cut-out snippets of a score.")
48     (datadir #f
49 "LilyPond prefix for data files (read-only).")
50     (debug-gc #f
51 "Dump memory debugging statistics.")
52     (debug-gc-assert-parsed-dead #f
53 "For memory debugging: Ensure that all
54 references to parsed objects are dead.  This is
55 an internal option, and is switched on
56 automatically for `-ddebug-gc'.")
57     (debug-lexer #f
58 "Debug the flex lexer.")
59     (debug-page-breaking-scoring #f
60 "Dump scores for many different page breaking
61 configurations.")
62     (debug-parser #f
63 "Debug the bison parser.")
64     (debug-property-callbacks #f
65 "Debug cyclic callback chains.")
66     (debug-skylines #f
67 "Debug skylines.")
68     (delete-intermediate-files #t
69 "Delete unusable, intermediate PostScript files.")
70     (dump-profile #f
71 "Dump memory and time information for each file.")
72     (dump-cpu-profile #f
73 "Dump timing information (system-dependent).")
74     (dump-signatures #f
75 "Dump output signatures of each system.  Used for
76 regression testing.")
77     (eps-box-padding #f
78 "Pad left edge of the output EPS bounding box by
79 given amount (in mm).")
80     (gs-load-fonts #f
81 "Load fonts via Ghostscript.")
82     (gs-load-lily-fonts #f
83 "Load only LilyPond fonts via Ghostscript.")
84     (gui #f
85 "Run LilyPond from a GUI and redirect stderr to
86 a log file.")
87     (help #f
88 "Show this help.")
89     (include-book-title-preview #t
90 "Include book titles in preview images.")
91     (include-eps-fonts #t
92 "Include fonts in separate-system EPS files.")
93     (job-count #f
94 "Process in parallel, using the given number of
95 jobs.")
96     (log-file #f
97 "If string FOO is given as argument, redirect
98 output to log file `FOO.log'.")
99     (midi-extension ,(if (eq? PLATFORM 'windows)
100                          "mid"
101                          "midi")
102 "Set the default file extension for MIDI output
103 file to given string.")
104     (old-relative #f
105 "Make \\relative mode for simultaneous music work
106 similar to chord syntax.")
107     (point-and-click #t
108 "Add point & click links to PDF output.")
109     (paper-size "a4"
110 "Set default paper size.")
111     (pixmap-format "png16m"
112 "Set GhostScript's output format for pixel images.")
113     (preview #f
114 "Create PNG and EPS preview images also.")
115     (print-pages #t
116 "Print pages in the normal way.")
117     (protected-scheme-parsing #t
118 "Continue when errors in inline scheme are caught
119 in the parser.  If #f, halt on errors and print
120 a stack trace.")
121     (profile-property-accesses #f
122 "Keep statistics of get_property() calls.")
123     (resolution 101
124 "Set resolution for generating PNG pixmaps to
125 given value (in dpi).")
126     (read-file-list #f
127 "Specify name of a file which contains a list of
128 input files to be processed.")
129     (relative-includes #f
130 "When processing an \\include command, look for
131 the included file relative to the current file
132 (instead of the root file)")
133     (safe #f
134 "Run in safer mode.")
135     (strict-infinity-checking #f
136 "Force a crash on encountering Inf and NaN
137 floating point exceptions.")
138     (strip-output-dir #t
139 "Don't use directories from input files while
140 constructing output file names.")
141     (separate-log-files #f
142 "For input files `FILE1.ly', `FILE2.ly', ...
143 output log data to files `FILE1.log',
144 `FILE2.log', ...")
145     (trace-memory-frequency #f
146 "Record Scheme cell usage this many times per
147 second.  Dump results to `FILE.stacks' and
148 `FILE.graph'.")
149     (trace-scheme-coverage #f
150 "Record coverage of Scheme files in `FILE.cov'.")
151     (show-available-fonts #f
152 "List available font names.")
153     (verbose ,(ly:command-line-verbose?)
154 "Value of the --verbose flag (read-only).")
155     (warning-as-error #f
156 "Change all warning and programming_error
157 messages into errors.")
158     ))
159
160 ;; Need to do this in the beginning.  Other parts of the Scheme
161 ;; initialization depend on these options.
162
163 (for-each (lambda (x)
164             (ly:add-option (car x) (cadr x) (caddr x)))
165           scheme-options-definitions)
166
167 (for-each (lambda (x)
168             (ly:set-option (car x) (cdr x)))
169           (eval-string (ly:command-line-options)))
170
171 (debug-set! stack 0)
172
173 (if (defined? 'set-debug-cell-accesses!)
174     (set-debug-cell-accesses! #f))
175
176                                         ;(set-debug-cell-accesses! 1000)
177
178 (use-modules (ice-9 regex)
179              (ice-9 safe)
180              (ice-9 format)
181              (ice-9 rdelim)
182              (ice-9 optargs)
183              (oop goops)
184              (srfi srfi-1)
185              (srfi srfi-13)
186              (srfi srfi-14)
187              (scm clip-region)
188              (scm memory-trace)
189              (scm coverage))
190
191 (define-public fancy-format
192   format)
193
194 (define-public (ergonomic-simple-format dest . rest)
195   "Like ice-9 format, but without the memory consumption."
196   (if (string? dest)
197       (apply simple-format (cons #f (cons dest rest)))
198       (apply simple-format (cons dest rest))))
199
200 (define format
201   ergonomic-simple-format)
202
203 ;; my display
204 (define-public (myd k v)
205   (display k)
206   (display ": ")
207   (display v)
208   (display ", ")
209   v)
210
211 (define-public (print . args)
212   (apply format (cons (current-output-port) args)))
213
214
215 ;;; General settings.
216 ;;;
217 ;;; Debugging evaluator is slower.  This should have a more sensible
218 ;;; default.
219
220 (if (or (ly:get-option 'verbose)
221         (ly:get-option 'trace-memory-frequency)
222         (ly:get-option 'trace-scheme-coverage))
223     (begin
224       (ly:set-option 'protected-scheme-parsing #f)
225       (debug-enable 'debug)
226       (debug-enable 'backtrace)
227       (read-enable 'positions)))
228
229 (if (ly:get-option 'trace-scheme-coverage)
230     (coverage:enable))
231
232 (if (ly:get-option 'warning-as-error)
233     (begin
234       (set! ly:warning ly:error)
235       (set! ly:programming-error ly:error)))
236
237 (define-public parser #f)
238
239
240 ;; gettext wrapper for guile < 1.7.2
241 (if (defined? 'gettext)
242     (define-public _ gettext)
243     (define-public _ ly:gettext))
244
245 (define-public (ly:load x)
246   (let* ((file-name (%search-load-path x)))
247     (if (ly:get-option 'verbose)
248         (ly:progress "[~A" file-name))
249     (if (not file-name)
250         (ly:error (_ "cannot find: ~A") x))
251     (primitive-load file-name)
252     (if (ly:get-option 'verbose)
253         (ly:progress "]\n"))))
254
255 (define-public DOS
256   (let ((platform (string-tokenize
257                    (vector-ref (uname) 0) char-set:letter+digit)))
258     (if (null? (cdr platform)) #f
259         (member (string-downcase (cadr platform)) '("95" "98" "me")))))
260
261 (case PLATFORM
262   ((windows)
263    (define native-getcwd
264      getcwd)
265
266    (define (slashify x)
267      (if (string-index x #\\)
268          x
269          (string-regexp-substitute
270           "//*" "/"
271           (string-regexp-substitute "\\\\" "/" x))))
272
273    ;; FIXME: this prints a warning.
274    (define-public (ly-getcwd)
275      (slashify (native-getcwd))))
276
277   (else
278    (define-public ly-getcwd
279      getcwd)))
280
281 (define-public (is-absolute? file-name)
282   (let ((file-name-length (string-length file-name)))
283     (if (= file-name-length 0)
284         #f
285         (or (eq? (string-ref file-name 0) #\/)
286             (and (eq? PLATFORM 'windows)
287                  (> file-name-length 2)
288                  (eq? (string-ref file-name 1) #\:)
289                  (eq? (string-ref file-name 2) #\/))))))
290
291 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
292
293 (define (type-check-list location signature arguments)
294   "Typecheck a list of arguments against a list of type predicates.
295 Print a message at LOCATION if any predicate failed."
296   (define (recursion-helper signature arguments count)
297     (define (helper pred? arg count)
298       (if (not (pred? arg))
299           (begin
300             (ly:input-message
301              location
302              (format
303               #f (_ "wrong type for argument ~a.  Expecting ~a, found ~s")
304               count (type-name pred?) arg))
305             #f)
306           #t))
307
308     (if (null? signature)
309         #t
310         (and (helper (car signature) (car arguments) count)
311              (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
312   (recursion-helper signature arguments 1))
313
314
315 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
316 ;; Safe definitions utility
317
318 (define safe-objects
319   (list))
320
321 (define-macro (define-safe-public arglist . body)
322   "Define a variable, export it, and mark it as safe, i.e. usable in
323 LilyPond safe mode.  The syntax is the same as `define*-public'."
324   (define (get-symbol arg)
325     (if (pair? arg)
326         (get-symbol (car arg))
327         arg))
328
329   (let ((safe-symbol (get-symbol arglist)))
330     `(begin
331        (define*-public ,arglist
332          ,@body)
333        (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
334                                 safe-objects))
335        ,safe-symbol)))
336
337 (define-safe-public (lilypond-version)
338   (string-join
339    (map (lambda (x) (if (symbol? x)
340                         (symbol->string x)
341                         (number->string x)))
342         (ly:version))
343    "."))
344
345 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
346 ;; init pitch system
347
348 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
349
350 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
351 ;; other files.
352
353 (define init-scheme-files
354   '("lily-library.scm"
355     "file-cache.scm"
356     "define-event-classes.scm"
357     "define-music-types.scm"
358     "output-lib.scm"
359     "c++.scm"
360     "chord-ignatzek-names.scm"
361     "chord-entry.scm"
362     "chord-generic-names.scm"
363     "stencil.scm"
364     "markup.scm"
365     "music-functions.scm"
366     "part-combiner.scm"
367     "autochange.scm"
368     "define-music-properties.scm"
369     "auto-beam.scm"
370     "chord-name.scm"
371
372     "parser-ly-from-scheme.scm"
373     "ly-syntax-constructors.scm"
374
375     "define-context-properties.scm"
376     "translation-functions.scm"
377     "script.scm"
378     "midi.scm"
379     "layout-beam.scm"
380     "parser-clef.scm"
381     "layout-slur.scm"
382     "font.scm"
383     "encoding.scm"
384
385     "flag-styles.scm"
386     "fret-diagrams.scm"
387     "harp-pedals.scm"
388     "predefined-fretboards.scm"
389     "define-markup-commands.scm"
390     "define-grob-properties.scm"
391     "define-grobs.scm"
392     "define-grob-interfaces.scm"
393     "define-stencil-commands.scm"
394     "titling.scm"
395
396     "paper.scm"
397     "backend-library.scm"
398     "x11-color.scm"
399
400     ;; must be after everything has been defined
401     "safe-lily.scm"))
402
403 (for-each ly:load init-scheme-files)
404
405 (set! type-p-name-alist
406       `((,boolean? . "boolean")
407         (,boolean-or-symbol? . "boolean or symbol")
408         (,char? . "char")
409         (,grob-list? . "list of grobs")
410         (,hash-table? . "hash table")
411         (,input-port? . "input port")
412         (,integer? . "integer")
413         (,list? . "list")
414         (,ly:context? . "context")
415         (,ly:dimension? . "dimension, in staff space")
416         (,ly:dir? . "direction")
417         (,ly:duration? . "duration")
418         (,ly:font-metric? . "font metric")
419         (,ly:grob? . "layout object")
420         (,ly:grob-array? . "array of grobs")
421         (,ly:input-location? . "input location")
422         (,ly:moment? . "moment")
423         (,ly:music? . "music")
424         (,ly:music-list? . "list of music objects")
425         (,ly:music-output? . "music output")
426         (,ly:pitch? . "pitch")
427         (,ly:translator? . "translator")
428         (,ly:simple-closure? . "simple closure")
429         (,ly:skyline-pair? . "pair of skylines")
430         (,ly:stencil? . "stencil")
431         (,markup-list? . "list of markups")
432         (,markup? . "markup")
433         (,number-or-grob? . "number or grob")
434         (,number-or-string? . "number or string")
435         (,number-pair? . "pair of numbers")
436         (,number? . "number")
437         (,output-port? . "output port")
438         (,pair? . "pair")
439         (,procedure? . "procedure")
440         (,rhythmic-location? . "rhythmic location")
441         (,scheme? . "any type")
442         (,string? . "string")
443         (,symbol? . "symbol")
444         (,vector? . "vector")))
445
446 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
447 ;; timing
448
449 (define (profile-measurements)
450   (let* ((t (times))
451          (stats (gc-stats)))
452     (list (- (+ (tms:cutime t)
453                 (tms:utime t))
454              (ly:assoc-get 'gc-time-taken stats))
455           (ly:assoc-get 'total-cells-allocated  stats 0))))
456
457 (define (dump-profile base last this)
458   (let* ((outname (format "~a.profile" (dir-basename base ".ly")))
459          (diff (map (lambda (y) (apply - y)) (zip this last))))
460     (ly:progress "\nWriting timing to ~a..." outname)
461     (format (open-file outname "w")
462             "time: ~a\ncells: ~a\n"
463             (if (ly:get-option 'dump-cpu-profile)
464                 (car diff)
465                 0)
466             (cadr diff))))
467
468 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
469 ;; debug memory leaks
470
471 (define gc-dumping
472   #f)
473
474 (define gc-protect-stat-count
475   0)
476
477 (define-public (dump-live-object-stats outfile)
478   (for-each (lambda (x)
479               (format outfile "~a: ~a\n" (car x) (cdr x)))
480             (sort (gc-live-object-stats)
481                   (lambda (x y)
482                     (string<? (car x) (car y))))))
483
484 (define-public (dump-gc-protects)
485   (set! gc-protect-stat-count (1+ gc-protect-stat-count))
486   (let* ((protects (sort (hash-table->alist (ly:protects))
487                          (lambda (a b)
488                            (< (object-address (car a))
489                               (object-address (car b))))))
490          (out-file-name (string-append
491                          "gcstat-" (number->string gc-protect-stat-count)
492                          ".scm"))
493          (outfile (open-file out-file-name "w")))
494     (set! gc-dumping #t)
495     (display (format "Dumping GC statistics ~a...\n" out-file-name))
496     (display (map (lambda (y)
497                     (let ((x (car y))
498                           (c (cdr y)))
499                       (display
500                        (format "~a (~a) = ~a\n" (object-address x) c x)
501                        outfile)))
502                   (filter
503                    (lambda (x)
504                      (not (symbol? (car x))))
505                    protects))
506              outfile)
507     (format outfile "\nprotected symbols: ~a\n"
508             (apply + (map (lambda (obj-count)
509                             (if (symbol? (car obj-count))
510                                 (cdr obj-count)
511                                 0))
512                           protects)))
513
514     ;; (display (ly:smob-protects))
515     (newline outfile)
516     (if (defined? 'gc-live-object-stats)
517         (let* ((stats #f))
518           (display "Live object statistics: GC'ing\n")
519           (ly:reset-all-fonts)
520           (gc)
521           (gc)
522           (display "Asserting dead objects\n")
523           (ly:set-option 'debug-gc-assert-parsed-dead #t)
524           (gc)
525           (ly:set-option 'debug-gc-assert-parsed-dead #f)
526           (set! stats (gc-live-object-stats))
527           (display "Dumping live object statistics.\n")
528           (dump-live-object-stats outfile)))
529     (newline outfile)
530     (let* ((stats (gc-stats)))
531       (for-each (lambda (sym)
532                   (display
533                    (format "~a ~a ~a\n"
534                            gc-protect-stat-count
535                            sym
536                            (let ((sym-stat (assoc sym stats)))
537                              (if sym-stat
538                                  (cdr sym-stat)
539                                  "?")))
540                    outfile))
541                 '(protected-objects bytes-malloced cell-heap-size)))
542     (set! gc-dumping #f)
543     (close-port outfile)))
544
545 (define (check-memory)
546   "Read `/proc/self' to check up on memory use."
547   (define (gulp-file name)
548     (let* ((file (open-input-file name))
549            (text (read-delimited "" file)))
550       (close file)
551       text))
552
553   (let* ((stat (gulp-file "/proc/self/status"))
554          (lines (string-split stat #\newline))
555          (interesting (filter identity
556                               (map
557                                (lambda (l)
558                                  (string-match "^VmData:[ \t]*([0-9]*) kB" l))
559                                lines)))
560          (mem (string->number (match:substring (car interesting) 1))))
561     (display (format  "VMDATA: ~a\n" mem))
562     (display (gc-stats))
563     (if (> mem 100000)
564         (begin (dump-gc-protects)
565                (raise 1)))))
566
567 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
568
569 (define (multi-fork count)
570   "Split this process into COUNT helpers.  Returns either a list of
571 PIDs or the number of the process."
572   (define (helper count acc)
573     (if (> count 0)
574         (let* ((pid (primitive-fork)))
575           (if (= pid 0)
576               (1- count)
577               (helper (1- count) (cons pid acc))))
578         acc))
579
580   (helper count '()))
581
582 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
583
584 (define-public (lilypond-main files)
585   "Entry point for LilyPond."
586   (eval-string (ly:command-line-code))
587   (if (ly:get-option 'help)
588       (begin (ly:option-usage)
589              (exit 0)))
590   (if (ly:get-option 'show-available-fonts)
591       (begin (ly:font-config-display-fonts)
592              (exit 0)))
593   (if (ly:get-option 'gui)
594       (gui-main files))
595   (if (null? files)
596       (begin (ly:usage)
597              (exit 2)))
598   (if (ly:get-option 'read-file-list)
599       (set! files
600             (filter (lambda (s)
601                       (> (string-length s) 0))
602                     (apply append
603                            (map (lambda (f)
604                                   (string-split (ly:gulp-file f) #\nl))
605                                 files)))))
606   (if (and (number? (ly:get-option 'job-count))
607            (>= (length files) (ly:get-option 'job-count)))
608       (let* ((count (ly:get-option 'job-count))
609              (split-todo (split-list files count))
610              (joblist (multi-fork count))
611              (errors '()))
612         (if (not (string-or-symbol? (ly:get-option 'log-file)))
613             (ly:set-option 'log-file "lilypond-multi-run"))
614         (if (number? joblist)
615             (begin (ly:set-option
616                     'log-file (format "~a-~a"
617                                       (ly:get-option 'log-file) joblist))
618                    (set! files (vector-ref split-todo joblist)))
619             (begin (ly:progress "\nForking into jobs:  ~a\n" joblist)
620                    (for-each
621                     (lambda (pid)
622                       (let* ((stat (cdr (waitpid pid))))
623                         (if (not (= stat 0))
624                             (set! errors
625                                   (acons (list-element-index joblist pid)
626                                          stat errors)))))
627                     joblist)
628                    (for-each
629                     (lambda (x)
630                       (let* ((job (car x))
631                              (state (cdr x))
632                              (logfile (format "~a-~a.log"
633                                               (ly:get-option 'log-file) job))
634                              (log (ly:gulp-file logfile))
635                              (len (string-length log))
636                              (tail (substring  log (max 0 (- len 1024)))))
637                         (if (status:term-sig state)
638                             (ly:message
639                              "\n\n~a\n"
640                              (format (_ "job ~a terminated with signal: ~a")
641                                      job (status:term-sig state)))
642                             (ly:message
643                              (_ "logfile ~a (exit ~a):\n~a")
644                              logfile (status:exit-val state) tail))))
645                     errors)
646                    (if (pair? errors)
647                        (ly:error "Children ~a exited with errors."
648                                  (map car errors)))
649                    ;; must overwrite individual entries
650                    (if (ly:get-option 'dump-profile)
651                        (dump-profile "lily-run-total"
652                                      '(0 0) (profile-measurements)))
653                    (exit (if (null? errors)
654                              0
655                              1))))))
656   (if (string-or-symbol? (ly:get-option 'log-file))
657       (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
658   (let ((failed (lilypond-all files)))
659     (if (ly:get-option 'trace-scheme-coverage)
660         (begin
661           (coverage:show-all (lambda (f)
662                                (string-contains f "lilypond")))))
663     (if (pair? failed)
664         (begin (ly:error (_ "failed files: ~S") (string-join failed))
665                (exit 1))
666         (begin
667           ;; HACK: be sure to exit with single newline
668           (ly:message "")
669           (exit 0)))))
670
671 (define-public (lilypond-all files)
672   (let* ((failed '())
673          (separate-logs (ly:get-option 'separate-log-files))
674          (ping-log
675           (if separate-logs
676               (open-file (if (string-or-symbol? (ly:get-option 'log-file))
677                              (format "~a.log" (ly:get-option 'log-file))
678                              "/dev/tty") "a") #f))
679          (do-measurements (ly:get-option 'dump-profile))
680          (handler (lambda (key failed-file)
681                     (set! failed (append (list failed-file) failed)))))
682     (gc)
683     (for-each
684      (lambda (x)
685        (let* ((start-measurements (if do-measurements
686                                       (profile-measurements)
687                                       #f))
688               (base (dir-basename x ".ly"))
689               (all-settings (ly:all-options)))
690          (if separate-logs
691              (ly:stderr-redirect (format "~a.log" base) "w"))
692          (if ping-log
693              (format ping-log "Processing ~a\n" base))
694          (if (ly:get-option 'trace-memory-frequency)
695              (mtrace:start-trace  (ly:get-option 'trace-memory-frequency)))
696          (lilypond-file handler x)
697          (if start-measurements
698              (dump-profile x start-measurements (profile-measurements)))
699          (if (ly:get-option 'trace-memory-frequency)
700              (begin (mtrace:stop-trace)
701                     (mtrace:dump-results base)))
702          (for-each (lambda (s)
703                      (ly:set-option (car s) (cdr s)))
704                    all-settings)
705          (ly:clear-anonymous-modules)
706          (ly:set-option 'debug-gc-assert-parsed-dead #t)
707          (gc)
708          (ly:set-option 'debug-gc-assert-parsed-dead #f)
709          (if (ly:get-option 'debug-gc)
710              (dump-gc-protects)
711              (if (= (random 40) 1)
712                  (ly:reset-all-fonts)))))
713      files)
714
715     ;; we want the failed-files notice in the aggregrate logfile.
716     (if ping-log
717         (format ping-log "Failed files: ~a\n" failed))
718     (if (ly:get-option 'dump-profile)
719         (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
720     failed))
721
722 (define (lilypond-file handler file-name)
723   (catch 'ly-file-failed
724          (lambda () (ly:parse-file file-name))
725          (lambda (x . args) (handler x file-name))))
726
727 (use-modules (scm editor))
728
729 (define-public (gui-main files)
730   (if (null? files)
731       (gui-no-files-handler))
732   (if (not (string? (ly:get-option 'log-file)))
733       (let* ((base (dir-basename (car files) ".ly"))
734              (log-name (string-append base ".log")))
735         (if (not (ly:get-option 'gui))
736             (ly:message (_ "Redirecting output to ~a...") log-name))
737         (ly:stderr-redirect log-name "w")
738         (ly:message "# -*-compilation-*-"))
739       (let ((failed (lilypond-all files)))
740         (if (pair? failed)
741             (begin
742               ;; ugh
743               (ly:stderr-redirect "foo" "r")
744               (system (get-editor-command log-name 0 0 0))
745               (ly:error (_ "failed files: ~S") (string-join failed))
746               ;; not reached?
747               (exit 1))
748             (exit 0)))))
749
750 (define (gui-no-files-handler)
751   (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
752          ;; FIXME: soft-code, localize
753          (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
754          (cmd (get-editor-command welcome-ly 0 0 0)))
755     (ly:message (_ "Invoking `~a'...\n") cmd)
756     (system cmd)
757     (exit 1)))