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