]> git.donarmstrong.com Git - lilypond.git/blob - scm/lily.scm
Merge branch 'master' of git://git.sv.gnu.org/lilypond
[lilypond.git] / scm / lily.scm
1 ;;;; lily.scm -- toplevel Scheme stuff
2 ;;;;
3 ;;;;  source file of the GNU LilyPond music typesetter
4 ;;;; 
5 ;;;; (c) 1998--2006 Jan Nieuwenhuizen <janneke@gnu.org>
6 ;;;; Han-Wen Nienhuys <hanwen@xs4all.nl>
7
8
9 (define (define-scheme-options)
10   (for-each (lambda (x)
11               (ly:add-option (car x) (cadr x) (caddr x)))
12           
13             `(
14
15               ;; NAMING: either
16
17               ;; - [subject-]object-object-verb +"ing"
18               ;; - [subject-]-verb-object-object
19
20               (anti-alias-factor 1 "render at higher resolution and scale down result\nto prevent jaggies in PNG")
21               (check-internal-types #f "check every property assignment for types")
22               (clip-systems #f "Generate cut-out snippets of a score")
23               (debug-gc #f "dump memory debugging statistics")
24               (debug-gc-assert-parsed-dead
25                #f "for memory debugging: ensure that all refs to parsed objects are dead.")
26               (debug-lexer #f "debug the flex lexer")
27               (debug-midi #f "generate human readable MIDI")
28               (debug-parser #f "debug the bison parser")
29               (debug-skylines #f "debug skylines")
30               (delete-intermediate-files #f
31                                          "delete unusable PostScript files")
32               (dump-signatures #f "dump output signatures of each system")
33               (dump-tweaks #f "dump page layout and tweaks for each score having the tweak-key layout property set.")
34               (gs-load-fonts #f
35                             "load fonts via Ghostscript.")
36               (include-book-title-preview #t "include book-titles in preview images.")
37               (include-eps-fonts #t "Include fonts in separate-system EPS files.")
38               (job-count #f "Process in parallel") 
39
40               (eps-box-padding #f "Pad EPS bounding box left edge by this much to guarantee alignment between systems")
41
42               (gui #f "running from gui; redirect stderr to log file")
43               (log-file #f "redirect output to log FILE.log")
44               (old-relative #f
45                             "relative for simultaneous music works
46 similar to chord syntax")
47               (object-keys #f
48                            "experimental mechanism for remembering tweaks")
49               (point-and-click #t "use point & click")
50               (paper-size "a4" "the default paper size")
51               (pixmap-format "png16m" "GS format to use for pixel images")
52               (protected-scheme-parsing #t "continue when finding errors in inline
53 scheme are caught in the parser. If off, halt 
54 on errors, and print a stack trace.")
55               (profile-property-accesses #f "keep statistics of get_property() calls.")
56               
57               (resolution 101 "resolution for generating PNG bitmaps")
58               (read-file-list #f "Read files to be processed from command line arguments")
59
60               (safe #f "Run safely")
61               (strict-infinity-checking #f "If yes, crash on encountering Inf/NaN")
62
63               (ttf-verbosity 0
64                              "how much verbosity for TTF font embedding?")
65
66               (show-available-fonts #f
67                                     "List  font names available.")
68
69               (verbose ,(ly:command-line-verbose?) "value for the --verbose flag")
70               )))
71
72
73 ;; need to do this in the beginning. Other parts of the
74 ;; Scheme init depend on these options.
75 ;;
76 (define-scheme-options)
77
78 (debug-set! stack 0)
79
80 (if (defined? 'set-debug-cell-accesses!)
81     (set-debug-cell-accesses! #f))
82
83                                         ;(set-debug-cell-accesses! 1000)
84
85 (use-modules (ice-9 regex)
86              (ice-9 safe)
87              (ice-9 optargs)
88              (oop goops)
89              (srfi srfi-1)
90              (srfi srfi-13)
91              (srfi srfi-14)
92              (scm clip-region)
93
94              )
95
96
97 ;; my display
98 (define-public (myd k v) (display k) (display ": ") (display v) (display ", "))
99
100 (define-public (print . args)
101   (apply format (cons (current-output-port) args)))
102
103
104 ;;; General settings
105 ;;; debugging evaluator is slower.  This should
106 ;;; have a more sensible default.
107
108 (if (ly:get-option 'verbose)
109     (begin
110       (ly:set-option 'protected-scheme-parsing #f)
111       (debug-enable 'debug)
112       (debug-enable 'backtrace)
113       (read-enable 'positions)))
114
115 (define-public tex-backend?
116   (member (ly:output-backend) '("texstr" "tex")))
117
118 (define-public parser #f)
119
120 (define-public (lilypond-version)
121   (string-join
122    (map (lambda (x) (if (symbol? x)
123                         (symbol->string x)
124                         (number->string x)))
125         (ly:version))
126    "."))
127
128
129 ;; TeX C++ code actually hooks into TEX_STRING_HASHLIMIT 
130 (define-public TEX_STRING_HASHLIMIT 10000000)
131
132
133
134 ;; gettext wrapper for guile < 1.7.2
135 (if (defined? 'gettext)
136     (define-public _ gettext)
137     (define-public _ ly:gettext))
138
139 (define-public (ly:load x)
140   (let* ((file-name (%search-load-path x)))
141     (if (ly:get-option 'verbose)
142         (ly:progress "[~A" file-name))
143     (if (not file-name)
144         (ly:error (_ "cannot find: ~A") x))
145     (primitive-load file-name)
146     (if (ly:get-option 'verbose)
147         (ly:progress "]"))))
148
149 ;; Cygwin
150 ;; #(CYGWIN_NT-5.1 Hostname 1.5.12(0.116/4/2) 2004-11-10 08:34 i686)
151 ;;
152 ;; Debian
153 ;; #(Linux hostname 2.4.27-1-686 #1 Fri Sep 3 06:28:00 UTC 2004 i686)
154 ;;
155 ;; Mingw
156 ;; #(Windows XP HOSTNAME build 2600 5.01 Service Pack 1 i686)
157 ;;
158
159 ;; ugh, code dup.
160 (define-public PLATFORM
161   (string->symbol
162    (string-downcase
163     (car (string-tokenize (vector-ref (uname) 0) char-set:letter)))))
164
165 (define-public DOS
166   (let ((platform (string-tokenize
167                    (vector-ref (uname) 0) char-set:letter+digit)))
168     (if (null? (cdr platform)) #f
169         (member (string-downcase (cadr platform)) '("95" "98" "me")))))
170
171 (case PLATFORM
172   ((windows)
173    (define native-getcwd getcwd)
174    (define (slashify x)
175      (if (string-index x #\\)
176          x
177          (string-regexp-substitute
178           "//*" "/"
179           (string-regexp-substitute "\\\\" "/" x))))
180    ;; FIXME: this prints a warning.
181    (define-public (ly-getcwd)
182      (slashify (native-getcwd))))
183   (else (define-public ly-getcwd getcwd)))
184
185 (define-public (is-absolute? file-name)
186   (let ((file-name-length (string-length file-name)))
187     (if (= file-name-length 0)
188         #f
189         (or (eq? (string-ref file-name 0) #\/)
190             (and (eq? PLATFORM 'windows)
191                  (> file-name-length 2)
192                  (eq? (string-ref file-name 1) #\:)
193                  (eq? (string-ref file-name 2) #\/))))))
194
195 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
196
197 (define (type-check-list location signature arguments)
198   "Typecheck a list of arguments against a list of type
199 predicates. Print a message at LOCATION if any predicate failed."
200
201   (define (recursion-helper signature arguments count) 
202     (define (helper pred? arg count) 
203       (if (not (pred? arg))
204
205           (begin
206             (ly:input-message
207              location
208              (format
209               #f (_ "wrong type for argument ~a.  Expecting ~a, found ~s")
210               count (type-name pred?) arg))
211             #f)
212           #t))
213
214     (if (null? signature)
215         #t
216         (and (helper (car signature) (car arguments) count)
217              (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
218
219   (recursion-helper signature arguments 1))
220
221 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
222 ;;  output
223
224
225 ;;(define-public (output-framework) (write "hello\n"))
226
227 (define output-tex-module
228   (make-module 1021 (list (resolve-interface '(scm output-tex)))))
229 (define output-ps-module
230   (make-module 1021 (list (resolve-interface '(scm output-ps)))))
231
232 (define-public (ps-output-expression expr port)
233   (display (eval expr output-ps-module) port))
234
235 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
236 ;; Safe definitions utility
237 (define safe-objects (list))
238
239 (define-macro (define-safe-public arglist . body)
240   "Define a variable, export it, and mark it as safe, ie usable in LilyPond safe mode.
241 The syntax is the same as `define*-public'."
242   (define (get-symbol arg)
243     (if (pair? arg)
244         (get-symbol (car arg))
245         arg))
246   (let ((safe-symbol (get-symbol arglist)))
247     `(begin
248        (define*-public ,arglist
249          ,@body)
250        (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
251                                 safe-objects))
252        ,safe-symbol)))
253
254 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
255 ;; init pitch system
256
257 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
258
259
260
261 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
262 ;; other files.
263
264 (for-each ly:load
265           ;; load-from-path
266           '("lily-library.scm"
267             "file-cache.scm"
268             "define-event-classes.scm"
269             "define-music-types.scm"
270             "output-lib.scm"
271             "c++.scm"
272             "chord-ignatzek-names.scm"
273             "chord-entry.scm"
274             "chord-generic-names.scm"
275             "stencil.scm"
276             "markup.scm"
277             "music-functions.scm"
278             "part-combiner.scm"
279             "autochange.scm"
280             "define-music-properties.scm"
281             "auto-beam.scm"
282             "chord-name.scm"
283
284             "parser-ly-from-scheme.scm"
285             "ly-syntax-constructors.scm"
286             
287             "define-context-properties.scm"
288             "translation-functions.scm"
289             "script.scm"
290             "midi.scm"
291             "layout-beam.scm"
292             "parser-clef.scm"
293             "layout-slur.scm"
294             "font.scm"
295             "encoding.scm"
296             
297             "fret-diagrams.scm"
298             "define-markup-commands.scm"
299             "define-grob-properties.scm"
300             "define-grobs.scm"
301             "define-grob-interfaces.scm"
302             "define-stencil-commands.scm"
303             "titling.scm"
304             
305             "paper.scm"
306             "backend-library.scm"
307             "x11-color.scm"
308
309             ;; must be after everything has been defined
310             "safe-lily.scm"))
311
312
313 (set! type-p-name-alist
314       `(
315         (,boolean-or-symbol? . "boolean or symbol")
316         (,boolean? . "boolean")
317         (,char? . "char")
318         (,grob-list? . "list of grobs")
319         (,hash-table? . "hash table")
320         (,input-port? . "input port")
321         (,integer? . "integer")
322         (,list? . "list")
323         (,ly:context? . "context")
324         (,ly:dimension? . "dimension, in staff space")
325         (,ly:dir? . "direction")
326         (,ly:duration? . "duration")
327         (,ly:grob? . "layout object")
328         (,ly:input-location? . "input location")
329         (,ly:moment? . "moment")
330         (,ly:music? . "music")
331         (,ly:pitch? . "pitch")
332         (,ly:translator? . "translator")
333         (,ly:font-metric? . "font metric")
334         (,ly:simple-closure? . "simple closure")
335         (,markup-list? . "list of markups")
336         (,markup? . "markup")
337         (,ly:music-list? . "list of music")
338         (,number-or-grob? . "number or grob")
339         (,number-or-string? . "number or string")
340         (,number-pair? . "pair of numbers")
341         (,number? . "number")
342         (,output-port? . "output port")   
343         (,pair? . "pair")
344         (,procedure? . "procedure")
345         (,rhythmic-location? . "rhythmic location")
346         (,scheme? . "any type")
347         (,string? . "string")
348         (,symbol? . "symbol")
349         (,vector? . "vector")))
350
351
352 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
353 ;; debug mem leaks
354
355 (define gc-dumping #f)
356 (define gc-protect-stat-count 0)
357 (define-public (dump-gc-protects)
358   (set! gc-protect-stat-count (1+ gc-protect-stat-count))
359   (let* ((protects (sort
360                     (hash-table->alist (ly:protects))
361                     (lambda (a b)
362                       (< (object-address (car a))
363                          (object-address (car b))))))
364
365          (out-file-name (string-append
366                          "gcstat-" (number->string gc-protect-stat-count)
367                          ".scm"))
368          (outfile    (open-file  out-file-name  "w")))
369
370     (set! gc-dumping #t)
371     (display (format "Dumping GC statistics ~a...\n" out-file-name))
372     (display
373      (map (lambda (y)
374             (let ((x (car y))
375                   (c (cdr y)))
376               (display 
377                (format "~a (~a) = ~a\n" (object-address x) c x)
378                outfile)))
379           (filter
380            (lambda (x)
381              (not (symbol? (car x))))
382            protects))
383      outfile)
384
385     (format outfile "\nprotected symbols: ~a\n"
386             (length (filter symbol?  (map car protects))))
387     
388              
389
390     ;; (display (ly:smob-protects))
391     (newline outfile)
392     (if (defined? 'gc-live-object-stats)
393         (let* ((stats #f))
394           (display "Live object statistics: GC'ing\n")
395           (ly:reset-all-fonts)
396           (gc)
397           (gc)
398           (ly:set-option 'debug-gc-assert-parsed-dead #t)
399           (gc)
400           (ly:set-option 'debug-gc-assert-parsed-dead #f)
401
402           (set! stats (gc-live-object-stats))
403           (display "Dumping live object statistics.\n")
404           
405           (for-each
406            (lambda (x)
407              (format outfile "~a: ~a\n" (car x) (cdr x)))
408            (sort (gc-live-object-stats)
409                  (lambda (x y)
410                    (string<? (car x) (car y)))))))
411
412
413     (newline outfile)
414     (let*
415         ((stats (gc-stats)))
416       
417       (for-each
418        (lambda (sym)
419          (display
420           (format "~a ~a ~a\n"
421                   gc-protect-stat-count
422                   sym
423                   (let ((sym-stat (assoc sym stats)))
424                     (if sym-stat 
425                         (cdr sym-stat)
426                         "?")))
427           outfile))
428        '(protected-objects bytes-malloced cell-heap-size
429                            
430                            )))
431
432     (set! gc-dumping #f)
433     
434     ))
435
436 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
437
438
439 (define (multi-fork count)
440   (define (helper count acc)
441     (if (> count 0)
442       (let*
443           ((pid  (primitive-fork)))
444         (if (= pid 0)
445             (1- count)
446             (helper (1- count) (cons pid acc))))
447       acc))
448   (helper count '()))
449
450
451 (define-public (lilypond-main files)
452   "Entry point for LilyPond."
453   
454   (define (no-files-handler)
455     (ly:usage)
456     (exit 2))
457
458   (if (ly:get-option 'gui)
459       (gui-main files))
460
461   (if (null? files)
462       (no-files-handler))
463
464   (if (ly:get-option 'read-file-list)
465       (set! files
466             (filter (lambda (s)
467                       (> (string-length s) 0))
468                     (apply append
469                            (map (lambda (f) (string-split (ly:gulp-file f) #\nl))
470                                 files)))
471             ))
472   
473   (if (and (number? (ly:get-option 'job-count))
474            (> (length files) (ly:get-option 'job-count)))
475       
476       (let*
477           ((count (ly:get-option 'job-count))
478            (split-todo (split-list files count)) 
479            (joblist (multi-fork count))
480            (errors '()))
481
482         (if (not (string-or-symbol? (ly:get-option 'log-file)))
483             (ly:set-option 'log-file "lilypond-multi-run"))
484         
485         (if (number? joblist)
486             (begin
487               (ly:set-option 'log-file (format "~a-~a"
488                                                (ly:get-option 'log-file) joblist))
489               (set! files (vector-ref split-todo joblist)))
490
491             (begin
492               (ly:progress "\nForking into jobs:  ~a\n" joblist)
493               (for-each
494                (lambda (pid)
495                  (let* ((stat (cdr (waitpid pid))))
496
497                    (if (not (= stat 0))
498                        (set! errors (cons (list-element-index joblist pid) errors)))))
499                joblist)
500
501               (for-each
502                (lambda (x)
503                  (let* ((logfile  (format "~a-~a.log"
504                                           (ly:get-option 'log-file) x))
505                         (log (ly:gulp-file logfile))
506                         (len (string-length log))
507                         (tail (substring  log (max 0 (- len 1024)))))
508
509                    (display (format "\n\nlogfile ~a:\n\n ~a" logfile tail))))
510
511                errors)
512
513               (if (pair? errors)
514                   (ly:error "Children ~a exited with errors." errors))
515
516             (exit (if (null? errors) 0 1))))))
517               
518            
519   (if (string-or-symbol? (ly:get-option 'log-file))
520       (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
521   
522   (let ((failed (lilypond-all files)))
523     (if (pair? failed)
524         (begin
525           (ly:error (_ "failed files: ~S") (string-join failed))
526           (exit 1))
527         (begin
528           ;; HACK: be sure to exit with single newline
529           (ly:message "")
530           (exit 0)))))
531
532 (define-public (lilypond-all files)
533
534
535   (if (ly:get-option 'show-available-fonts)
536       (begin
537         (ly:font-config-display-fonts)
538         (exit 0)
539         ))
540   
541   (let* ((failed '())
542          (first #t)
543          (handler (lambda (key failed-file)
544                     (set! failed (append (list failed-file) failed)))))
545
546     (for-each
547      (lambda (x)
548
549        ;; We don't carry info across file boundaries
550        (if first
551            (set! first #f)
552            (gc))
553        
554        (lilypond-file handler x)
555        (ly:clear-anonymous-modules)
556        (if (ly:get-option 'debug-gc)
557            (dump-gc-protects)
558            (if (= (random 40) 1)
559                (ly:reset-all-fonts))))
560
561      files)
562     failed))
563
564 (define (lilypond-file handler file-name)
565   (catch 'ly-file-failed
566          (lambda () (ly:parse-file file-name))
567          (lambda (x . args) (handler x file-name))))
568
569 (use-modules (scm editor))
570
571 (define-public (gui-main files)
572   (if (null? files)
573       (gui-no-files-handler))
574
575   (if (not (string? (ly:get-option 'log-file)))
576       (let* ((base (basename (car files) ".ly"))
577              (log-name (string-append base ".log")))
578         (if (not (ly:get-option 'gui))
579             (ly:message (_ "Redirecting output to ~a...") log-name))
580         (ly:stderr-redirect log-name "w")
581         (ly:message "# -*-compilation-*-"))
582     
583     (let ((failed (lilypond-all files)))
584       (if (pair? failed)
585           (begin
586             ;; ugh
587             (ly:stderr-redirect "foo" "r")
588             (system (get-editor-command log-name 0 0 0))
589             (ly:error (_ "failed files: ~S") (string-join failed))
590             ;; not reached?
591             (exit 1))
592           (exit 0)))))
593
594 (define (gui-no-files-handler)
595   (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
596          ;; FIXME: soft-code, localize
597          (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
598          (cmd (get-editor-command welcome-ly 0 0 0)))
599     (ly:message (_ "Invoking `~a'...") cmd)
600     (system cmd)
601     (exit 1)))