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