]> git.donarmstrong.com Git - lilypond.git/blob - scm/lily.scm
[scm]: Use two spaces after full stop in doc strings.
[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 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     "chord-name.scm"
413     "bezier-tools.scm"
414     "parser-ly-from-scheme.scm"
415     "ly-syntax-constructors.scm"
416
417     "define-context-properties.scm"
418     "translation-functions.scm"
419     "script.scm"
420     "midi.scm"
421     "layout-beam.scm"
422     "parser-clef.scm"
423     "layout-slur.scm"
424     "font.scm"
425     "encoding.scm"
426
427     "flag-styles.scm"
428     "fret-diagrams.scm"
429     "tablature.scm"
430     "harp-pedals.scm"
431     "define-woodwind-diagrams.scm"
432     "display-woodwind-diagrams.scm"
433     "predefined-fretboards.scm"
434     "define-markup-commands.scm"
435     "define-grob-properties.scm"
436     "define-grobs.scm"
437     "define-grob-interfaces.scm"
438     "define-stencil-commands.scm"
439     "titling.scm"
440
441     "paper.scm"
442     "backend-library.scm"
443     "x11-color.scm"
444
445     ;; must be after everything has been defined
446     "safe-lily.scm"))
447
448 (for-each ly:load init-scheme-files)
449
450 (define-public r5rs-primary-predicates
451   `((,boolean? . "boolean")
452     (,char? . "character")
453     (,number? . "number")
454     (,pair? . "pair")
455     (,port? . "port")
456     (,procedure? . "procedure")
457     (,string? . "string")
458     (,symbol? . "symbol")
459     (,vector? . "vector")))
460
461 (define-public r5rs-secondary-predicates
462   `((,char-alphabetic? . "alphabetic character")
463     (,char-lower-case? . "lower-case character")
464     (,char-numeric? . "numeric character")
465     (,char-upper-case? . "upper-case character")
466     (,char-whitespace? . "whitespace character")
467
468     (,complex? . "complex number")
469     (,even? . "even number")
470     (,exact? . "exact number")
471     (,inexact? . "inexact number")
472     (,integer? . "integer")
473     (,negative? . "negative number")
474     (,odd? . "odd number")
475     (,positive? . "positive number")
476     (,rational? . "rational number")
477     (,real? . "real number")
478     (,zero? . "zero")
479
480     (,list? . "list")
481     (,null? . "null")
482
483     (,input-port? . "input port")
484     (,output-port? . "output port")
485
486     ;; would this ever be used?
487     (,eof-object? . "end-of-file object")
488     ))
489
490 (define-public guile-predicates
491   `((,hash-table? . "hash table")
492   ))
493
494 (define-public lilypond-scheme-predicates
495   `((,boolean-or-symbol? . "boolean or symbol")
496     (,color? . "color")
497     (,cheap-list? . "list")
498     (,grob-list? . "list of grobs")
499     ;; this is built on cheap-list
500     (,list-or-symbol? . "list or symbol")
501     (,markup? . "markup")
502     (,markup-command-list? . "markup command list")
503     (,markup-list? . "markup list")
504     (,moment-pair? . "pair of moment objects")
505     (,number-or-grob? . "number or grob")
506     (,number-or-pair? . "number or pair")
507     (,number-or-string? . "number or string")
508     (,number-pair? . "pair of numbers")
509     (,rhythmic-location? . "rhythmic location")
510     (,scheme? . "any type")
511     (,string-or-pair? . "string or pair")
512     (,string-or-symbol? . "string or symbol")
513     ))
514
515 (define-public lilypond-exported-predicates
516   `((,ly:box? . "box")
517     (,ly:context? . "context")
518     (,ly:dimension? . "dimension, in staff space")
519     (,ly:dir? . "direction")
520     (,ly:dispatcher? . "dispatcher")
521     (,ly:duration? . "duration")
522     (,ly:font-metric? . "font metric")
523     (,ly:grob? . "graphical (layout) object")
524     (,ly:grob-array? . "array of grobs")
525     (,ly:input-location? . "input location")
526     (,ly:item? . "item")
527     (,ly:iterator? . "iterator")
528     (,ly:lily-lexer? . "lily-lexer")
529     (,ly:lily-parser? . "lily-parser")
530     (,ly:listener? . "listener")
531     (,ly:moment? . "moment")
532     (,ly:music? . "music")
533     (,ly:music-function? . "music function")
534     (,ly:music-list? . "list of music objects")
535     (,ly:music-output? . "music output")
536     (,ly:otf-font? . "OpenType font")
537     (,ly:output-def? . "output definition")
538     (,ly:page-marker? . "page marker")
539     (,ly:pango-font? . "pango font")
540     (,ly:paper-book? . "paper book")
541     (,ly:paper-system? . "paper-system Prob")
542     (,ly:pitch? . "pitch")
543     (,ly:prob? . "property object")
544     (,ly:score? . "score")
545     (,ly:simple-closure? . "simple closure")
546     (,ly:skyline? . "skyline")
547     (,ly:skyline-pair? . "pair of skylines")
548     (,ly:source-file? . "source file")
549     (,ly:spanner? . "spanner")
550     (,ly:stencil? . "stencil")
551     (,ly:stream-event? . "stream event")
552     (,ly:translator? . "translator")
553     (,ly:translator-group? . "translator group")
554     ))
555
556
557 (set! type-p-name-alist
558       (append r5rs-primary-predicates
559               r5rs-secondary-predicates
560               guile-predicates
561               lilypond-scheme-predicates
562               lilypond-exported-predicates))
563
564
565 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
566 ;; timing
567
568 (define (profile-measurements)
569   (let* ((t (times))
570          (stats (gc-stats)))
571     (list (- (+ (tms:cutime t)
572                 (tms:utime t))
573              (assoc-get 'gc-time-taken stats))
574           (assoc-get 'total-cells-allocated  stats 0))))
575
576 (define (dump-profile base last this)
577   (let* ((outname (format "~a.profile" (dir-basename base ".ly")))
578          (diff (map (lambda (y) (apply - y)) (zip this last))))
579     (ly:progress "\nWriting timing to ~a..." outname)
580     (format (open-file outname "w")
581             "time: ~a\ncells: ~a\n"
582             (if (ly:get-option 'dump-cpu-profile)
583                 (car diff)
584                 0)
585             (cadr diff))))
586
587 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
588 ;; debug memory leaks
589
590 (define gc-dumping
591   #f)
592
593 (define gc-protect-stat-count
594   0)
595
596 (define-public (dump-live-object-stats outfile)
597   (for-each (lambda (x)
598               (format outfile "~a: ~a\n" (car x) (cdr x)))
599             (sort (gc-live-object-stats)
600                   (lambda (x y)
601                     (string<? (car x) (car y))))))
602
603 (define-public (dump-gc-protects)
604   (set! gc-protect-stat-count (1+ gc-protect-stat-count))
605   (let* ((protects (sort (hash-table->alist (ly:protects))
606                          (lambda (a b)
607                            (< (object-address (car a))
608                               (object-address (car b))))))
609          (out-file-name (string-append
610                          "gcstat-" (number->string gc-protect-stat-count)
611                          ".scm"))
612          (outfile (open-file out-file-name "w")))
613     (set! gc-dumping #t)
614     (display (format "Dumping GC statistics ~a...\n" out-file-name))
615     (display (map (lambda (y)
616                     (let ((x (car y))
617                           (c (cdr y)))
618                       (display
619                        (format "~a (~a) = ~a\n" (object-address x) c x)
620                        outfile)))
621                   (filter
622                    (lambda (x)
623                      (not (symbol? (car x))))
624                    protects))
625              outfile)
626     (format outfile "\nprotected symbols: ~a\n"
627             (apply + (map (lambda (obj-count)
628                             (if (symbol? (car obj-count))
629                                 (cdr obj-count)
630                                 0))
631                           protects)))
632
633     ;; (display (ly:smob-protects))
634     (newline outfile)
635     (if (defined? 'gc-live-object-stats)
636         (let* ((stats #f))
637           (display "Live object statistics: GC'ing\n")
638           (ly:reset-all-fonts)
639           (gc)
640           (gc)
641           (display "Asserting dead objects\n")
642           (ly:set-option 'debug-gc-assert-parsed-dead #t)
643           (gc)
644           (ly:set-option 'debug-gc-assert-parsed-dead #f)
645           (set! stats (gc-live-object-stats))
646           (display "Dumping live object statistics.\n")
647           (dump-live-object-stats outfile)))
648     (newline outfile)
649     (let* ((stats (gc-stats)))
650       (for-each (lambda (sym)
651                   (display
652                    (format "~a ~a ~a\n"
653                            gc-protect-stat-count
654                            sym
655                            (assoc-get sym stats "?"))
656
657                    outfile))
658                 '(protected-objects bytes-malloced cell-heap-size)))
659     (set! gc-dumping #f)
660     (close-port outfile)))
661
662 (define (check-memory)
663   "Read `/proc/self' to check up on memory use."
664   (define (gulp-file name)
665     (let* ((file (open-input-file name))
666            (text (read-delimited "" file)))
667       (close file)
668       text))
669
670   (let* ((stat (gulp-file "/proc/self/status"))
671          (lines (string-split stat #\newline))
672          (interesting (filter identity
673                               (map
674                                (lambda (l)
675                                  (string-match "^VmData:[ \t]*([0-9]*) kB" l))
676                                lines)))
677          (mem (string->number (match:substring (car interesting) 1))))
678     (display (format  "VMDATA: ~a\n" mem))
679     (display (gc-stats))
680     (if (> mem 100000)
681         (begin (dump-gc-protects)
682                (raise 1)))))
683
684 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
685
686 (define (multi-fork count)
687   "Split this process into COUNT helpers.  Returns either a list of
688 PIDs or the number of the process."
689   (define (helper count acc)
690     (if (> count 0)
691         (let* ((pid (primitive-fork)))
692           (if (= pid 0)
693               (1- count)
694               (helper (1- count) (cons pid acc))))
695         acc))
696
697   (helper count '()))
698
699 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
700
701 (define* (ly:exit status #:optional (silently #f))
702   "Exit function for lilypond"
703   (if (not silently)
704       (case status
705         ((0) (ly:success (_ "Compilation successfully completed")))
706         ((1) (ly:warning (_ "Compilation completed with warnings or errors")))
707         (else (ly:message ""))))
708   (exit status))
709
710 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
711
712 (define-public (lilypond-main files)
713   "Entry point for LilyPond."
714   (eval-string (ly:command-line-code))
715   (if (ly:get-option 'help)
716       (begin (ly:option-usage)
717              (ly:exit 0 #t)))
718   (if (ly:get-option 'show-available-fonts)
719       (begin (ly:font-config-display-fonts)
720              (ly:exit 0 #t)))
721   (if (ly:get-option 'gui)
722       (gui-main files))
723   (if (null? files)
724       (begin (ly:usage)
725              (ly:exit 2 #t)))
726   (if (ly:get-option 'read-file-list)
727       (set! files
728             (filter (lambda (s)
729                       (> (string-length s) 0))
730                     (apply append
731                            (map (lambda (f)
732                                   (string-split (ly:gulp-file f) #\nl))
733                                 files)))))
734   (if (and (number? (ly:get-option 'job-count))
735            (>= (length files) (ly:get-option 'job-count)))
736       (let* ((count (ly:get-option 'job-count))
737              (split-todo (split-list files count))
738              (joblist (multi-fork count))
739              (errors '()))
740         (if (not (string-or-symbol? (ly:get-option 'log-file)))
741             (ly:set-option 'log-file "lilypond-multi-run"))
742         (if (number? joblist)
743             (begin (ly:set-option
744                     'log-file (format "~a-~a"
745                                       (ly:get-option 'log-file) joblist))
746                    (set! files (vector-ref split-todo joblist)))
747             (begin (ly:progress "\nForking into jobs:  ~a\n" joblist)
748                    (for-each
749                     (lambda (pid)
750                       (let* ((stat (cdr (waitpid pid))))
751                         (if (not (= stat 0))
752                             (set! errors
753                                   (acons (list-element-index joblist pid)
754                                          stat errors)))))
755                     joblist)
756                    (for-each
757                     (lambda (x)
758                       (let* ((job (car x))
759                              (state (cdr x))
760                              (logfile (format "~a-~a.log"
761                                               (ly:get-option 'log-file) job))
762                              (log (ly:gulp-file logfile))
763                              (len (string-length log))
764                              (tail (substring  log (max 0 (- len 1024)))))
765                         (if (status:term-sig state)
766                             (ly:message
767                              "\n\n~a\n"
768                              (format (_ "job ~a terminated with signal: ~a")
769                                      job (status:term-sig state)))
770                             (ly:message
771                              (_ "logfile ~a (exit ~a):\n~a")
772                              logfile (status:exit-val state) tail))))
773                     errors)
774                    (if (pair? errors)
775                        (ly:error "Children ~a exited with errors."
776                                  (map car errors)))
777                    ;; must overwrite individual entries
778                    (if (ly:get-option 'dump-profile)
779                        (dump-profile "lily-run-total"
780                                      '(0 0) (profile-measurements)))
781                    (if (null? errors)
782                        (ly:exit 0 #f)
783                        (ly:exit 1 #f))))))
784
785   (if (string-or-symbol? (ly:get-option 'log-file))
786       (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
787   (let ((failed (lilypond-all files)))
788     (if (ly:get-option 'trace-scheme-coverage)
789         (begin
790           (coverage:show-all (lambda (f)
791                                (string-contains f "lilypond")))))
792     (if (pair? failed)
793         (begin (ly:error (_ "failed files: ~S") (string-join failed))
794                (ly:exit 1 #f))
795         (begin
796           (ly:exit 0 #f)))))
797
798
799 (define-public (lilypond-all files)
800   (let* ((failed '())
801          (separate-logs (ly:get-option 'separate-log-files))
802          (ping-log
803           (if separate-logs
804               (open-file (if (string-or-symbol? (ly:get-option 'log-file))
805                              (format "~a.log" (ly:get-option 'log-file))
806                              "/dev/stderr") "a") #f))
807          (do-measurements (ly:get-option 'dump-profile))
808          (handler (lambda (key failed-file)
809                     (set! failed (append (list failed-file) failed)))))
810     (gc)
811     (for-each
812      (lambda (x)
813        (let* ((start-measurements (if do-measurements
814                                       (profile-measurements)
815                                       #f))
816               (base (dir-basename x ".ly"))
817               (all-settings (ly:all-options)))
818          (if separate-logs
819              (ly:stderr-redirect (format "~a.log" base) "w"))
820          (if ping-log
821              (format ping-log "Processing ~a\n" base))
822          (if (ly:get-option 'trace-memory-frequency)
823              (mtrace:start-trace  (ly:get-option 'trace-memory-frequency)))
824          (lilypond-file handler x)
825          (if start-measurements
826              (dump-profile x start-measurements (profile-measurements)))
827          (if (ly:get-option 'trace-memory-frequency)
828              (begin (mtrace:stop-trace)
829                     (mtrace:dump-results base)))
830          (for-each (lambda (s)
831                      (ly:set-option (car s) (cdr s)))
832                    all-settings)
833          (ly:set-option 'debug-gc-assert-parsed-dead #t)
834          (gc)
835          (ly:set-option 'debug-gc-assert-parsed-dead #f)
836          (if (ly:get-option 'debug-gc)
837              (dump-gc-protects)
838              (ly:reset-all-fonts))))
839      files)
840
841     ;; Ensure a notice re failed files is written to aggregate logfile.
842     (if ping-log
843         (format ping-log "Failed files: ~a\n" failed))
844     (if (ly:get-option 'dump-profile)
845         (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
846     failed))
847
848 (define (lilypond-file handler file-name)
849   (catch 'ly-file-failed
850          (lambda () (ly:parse-file file-name))
851          (lambda (x . args) (handler x file-name))))
852
853 (use-modules (scm editor))
854
855 (define-public (gui-main files)
856   (if (null? files)
857       (gui-no-files-handler))
858   (if (not (string? (ly:get-option 'log-file)))
859       (let* ((base (dir-basename (car files) ".ly"))
860              (log-name (string-append base ".log")))
861         (if (not (ly:get-option 'gui))
862             (ly:message (_ "Redirecting output to ~a...") log-name))
863         (ly:stderr-redirect log-name "w")
864         (ly:message "# -*-compilation-*-"))
865       (let ((failed (lilypond-all files)))
866         (if (pair? failed)
867             (begin
868               ;; ugh
869               (ly:stderr-redirect "foo" "r")
870               (system (get-editor-command log-name 0 0 0))
871               (ly:error (_ "failed files: ~S") (string-join failed))
872               ;; not reached?
873               (exit 1))
874             (ly:exit 0 #f)))))
875
876 (define (gui-no-files-handler)
877   (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
878          ;; FIXME: soft-code, localize
879          (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
880          (cmd (get-editor-command welcome-ly 0 0 0)))
881     (ly:message (_ "Invoking `~a'...\n") cmd)
882     (system cmd)
883     (ly:exit 1 #f)))