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