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