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