]> git.donarmstrong.com Git - lilypond.git/blob - scm/framework-ps.scm
Issue 4901: Improve `-dgs-load-fonts` option for OTC fonts
[lilypond.git] / scm / framework-ps.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 2004--2015 Han-Wen Nienhuys <hanwen@xs4all.nl>
4 ;;;;
5 ;;;; LilyPond is free software: you can redistribute it and/or modify
6 ;;;; it under the terms of the GNU General Public License as published by
7 ;;;; the Free Software Foundation, either version 3 of the License, or
8 ;;;; (at your option) any later version.
9 ;;;;
10 ;;;; LilyPond is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 ;;;; GNU General Public License for more details.
14 ;;;;
15 ;;;; You should have received a copy of the GNU General Public License
16 ;;;; along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
17
18 (define-module (scm framework-ps))
19
20 ;;; this is still too big a mess.
21
22 (use-modules (ice-9 string-fun)
23              (guile)
24              (scm page)
25              (scm paper-system)
26              (srfi srfi-1)
27              (srfi srfi-13)
28              (scm clip-region)
29              (lily))
30
31 (define format ergonomic-simple-format)
32
33 (define framework-ps-module (current-module))
34
35 ;;(define pdebug stderr)
36 (define (pdebug . rest) #f)
37
38 (define-public (ps-font-command font)
39   (let* ((name (ly:font-file-name font))
40          (magnify (ly:font-magnification font)))
41     (string-append
42      "magfont"
43      (ly:string-substitute
44       " " "_"
45       (ly:string-substitute
46        "/" "_"
47        (ly:string-substitute
48         "%" "_" name)))
49      "m" (string-encode-integer (inexact->exact (round (* 1000 magnify)))))))
50
51 (define (ps-define-pango-pf pango-pf font-name scaling)
52   "")
53
54 (define (ps-define-font font font-name scaling)
55   (if (ly:bigpdfs)
56       (string-append
57        "/" (ps-font-command font) "-N"
58        " { /" font-name "-N"
59        " " (ly:number->string scaling) " output-scale div selectfont }"
60        " bind def\n"
61        "/" (ps-font-command font) "-S"
62        " { /" font-name "-S"
63        " " (ly:number->string scaling) " output-scale div selectfont }"
64        " bind def\n"
65        "/" (ps-font-command font) "-O"
66        " { /" font-name "-O"
67        " " (ly:number->string scaling) " output-scale div selectfont }"
68        " bind def\n"
69        "/help" font-name " {\n  gsave\n  1 setgray\n  /"
70        font-name "-N"
71        " 0.001 selectfont 0 0 moveto <01> show\n  /"
72        font-name "-S"
73        " 0.001 selectfont 0 0 moveto <01> show\n  /"
74        font-name "-O"
75        " 0.001 selectfont 0 0 moveto <01> show\n  grestore\n} def\n")
76       (string-append
77        "/" (ps-font-command font)
78        " { /" font-name
79        " " (ly:number->string scaling) " output-scale div selectfont }"
80        " bind def\n")))
81
82 ;; FIXME: duplicated in other output backends
83 ;; FIXME: silly interface name
84 (define (output-variables layout)
85   ;; FIXME: duplicates output-layout's scope-entry->string, mostly
86   (define (value->string val)
87     (cond
88      ((string? val) (string-append "(" val ")"))
89      ((symbol? val) (symbol->string val))
90      ((number? val) (number->string val))
91      (else "")))
92
93   (define (output-entry ps-key ly-key)
94     (string-append
95      "/" ps-key " "
96      (value->string (ly:output-def-lookup layout ly-key)) " def\n"))
97
98   (string-append
99    "/lily-output-units "
100    (number->string (/ (ly:bp 1))) " def %% millimeter\n"
101    (output-entry "staff-line-thickness" 'line-thickness)
102    (output-entry "line-width" 'line-width)
103    (output-entry "paper-size" 'papersizename)
104    (output-entry "staff-height" 'staff-height)  ;junkme.
105    "/output-scale "
106    (number->string (ly:output-def-lookup layout 'output-scale)) " def\n"
107    (output-entry "page-height" 'paper-height)
108    (output-entry "page-width" 'paper-width)
109    (if (ly:get-option 'strokeadjust) "true setstrokeadjust\n" "")
110    ))
111
112 (define (dump-page outputter page page-number page-count landscape?)
113   (ly:outputter-dump-string
114    outputter
115    (string-append
116     (format #f "%%Page: ~a ~a\n" page-number page-number)
117     "%%BeginPageSetup\n"
118     (if landscape?
119         "page-width output-scale lily-output-units mul mul 0 translate 90 rotate\n"
120         "")
121     "%%EndPageSetup\n"
122     "\n"
123     "gsave 0 paper-height translate set-ps-scale-to-lily-scale\n"
124     "/helpEmmentaler-Brace where {pop helpEmmentaler-Brace} if\n"
125     "/helpEmmentaler-11 where {pop helpEmmentaler-11} if\n"
126     "/helpEmmentaler-13 where {pop helpEmmentaler-13} if\n"
127     "/helpEmmentaler-14 where {pop helpEmmentaler-14} if\n"
128     "/helpEmmentaler-16 where {pop helpEmmentaler-16} if\n"
129     "/helpEmmentaler-18 where {pop helpEmmentaler-18} if\n"
130     "/helpEmmentaler-20 where {pop helpEmmentaler-20} if\n"
131     "/helpEmmentaler-23 where {pop helpEmmentaler-23} if\n"
132     "/helpEmmentaler-26 where {pop helpEmmentaler-26} if\n"))
133   (ly:outputter-dump-stencil outputter page)
134   (ly:outputter-dump-string outputter "stroke grestore\nshowpage\n"))
135
136 (define (supplies-or-needs paper load-fonts?)
137   (define (extract-names font)
138     (if (ly:pango-font? font)
139         (map car (ly:pango-font-physical-fonts font))
140         (list (ly:font-name font))))
141
142   (let* ((fonts (ly:paper-fonts paper))
143          (names (append-map extract-names fonts)))
144     (string-concatenate
145      (map (lambda (f)
146             (format #f
147                     (if load-fonts?
148                         "%%DocumentSuppliedResources: font ~a\n"
149                         "%%DocumentNeededResources: font ~a\n")
150                     f))
151           (uniq-list (sort names string<?))))))
152
153 (define (eps-header paper bbox load-fonts?)
154   (string-append "%!PS-Adobe-2.0 EPSF-2.0\n"
155                  "%%Creator: LilyPond " (lilypond-version) "\n"
156                  "%%BoundingBox: "
157                  (string-join (map ly:number->string bbox) " ") "\n"
158                  "%%Orientation: "
159                  (if (eq? (ly:output-def-lookup paper 'landscape) #t)
160                      "Landscape\n"
161                      "Portrait\n")
162                  (supplies-or-needs paper load-fonts?)
163                  "%%EndComments\n"))
164
165 (define (ps-document-media paper)
166   (let* ((w (/ (*
167                 (ly:output-def-lookup paper 'output-scale)
168                 (ly:output-def-lookup paper 'paper-width)) (ly:bp 1)))
169          (h (/ (*
170                 (ly:output-def-lookup paper 'paper-height)
171                 (ly:output-def-lookup paper 'output-scale))
172                (ly:bp 1)))
173          (landscape? (eq? (ly:output-def-lookup paper 'landscape) #t)))
174     (ly:format "%%DocumentMedia: ~a ~2f ~2f ~a ~a ~a\n"
175                (ly:output-def-lookup paper 'papersizename)
176                (if landscape? h w)
177                (if landscape? w h)
178                80   ;; weight
179                "()" ;; color
180                "()" ;; type
181                )))
182
183 (define (file-header paper page-count load-fonts?)
184   (string-append "%!PS-Adobe-3.0\n"
185                  "%%Creator: LilyPond " (lilypond-version) "\n"
186                  "%%Pages: " (number->string page-count) "\n"
187                  "%%PageOrder: Ascend\n"
188                  "%%Orientation: "
189                  (if (eq? (ly:output-def-lookup paper 'landscape) #t)
190                      "Landscape\n"
191                      "Portrait\n")
192                  (ps-document-media paper)
193                  (supplies-or-needs paper load-fonts?)
194                  "%%EndComments\n"))
195
196 (define (procset file-name)
197   (format #f
198           "%%BeginResource: procset (~a) 1 0
199 ~a
200 %%EndResource
201 "
202           file-name (cached-file-contents file-name)))
203
204 (define (embed-document file-name)
205   (format #f "%%BeginDocument: ~a
206 ~a
207 %%EndDocument
208 "
209           file-name (cached-file-contents file-name)))
210
211 (define (setup-variables paper)
212   (string-append
213    "\n"
214    (define-fonts paper ps-define-font ps-define-pango-pf)
215    (output-variables paper)))
216
217 (define (cff-font? font)
218   (let* ((cff-string (ly:otf-font-table-data font "CFF ")))
219     (> (string-length cff-string) 0)))
220
221 (define-public (ps-embed-cff body font-set-name version)
222   (let* ((binary-data
223           (string-append
224            (format #f "/~a ~s StartData " font-set-name (string-length body))
225            body))
226          (header
227           (format #f
228                   "%%BeginResource: font ~a
229 %!PS-Adobe-3.0 Resource-FontSet
230 %%DocumentNeededResources: ProcSet (FontSetInit)
231 %%Title: (FontSet/~a)
232 %%Version: ~s
233 %%EndComments
234 %%IncludeResource: ProcSet (FontSetInit)
235 %%BeginResource: FontSet (~a)
236 /FontSetInit /ProcSet findresource begin
237 %%BeginData: ~s Binary Bytes
238 "
239                   font-set-name font-set-name version font-set-name
240                   (string-length binary-data)))
241          (footer "\n%%EndData
242 %%EndResource
243 %%EndResource\n"))
244     (string-append header
245                    binary-data
246                    footer)))
247
248 (define (write-preamble paper load-fonts? port)
249   (define (internal-font? font-name-filename)
250     (let* ((font (car font-name-filename))
251            (file-name (caddr font-name-filename))
252            (font-file-name (ly:find-file (format #f "~a.otf" file-name))))
253       (and font
254            (cff-font? font)
255            font-file-name
256            (string-contains font-file-name
257                             (ly:get-option 'datadir)))))
258
259   (define (load-font-via-GS font-name-filename)
260     (define (is-collection-font? file-name)
261       (let ((port (open-file file-name "rb")))
262         (if (eq? (read-char port) #\t)
263             (if (eq? (read-char port) #\t)
264                 (if (eq? (read-char port) #\c)
265                     (if (eq? (read-char port) #\f)
266                         #t
267                         #f)
268                     #f)
269                 #f)
270             #f)))
271
272     (define (ps-load-file file-name)
273       (if (string? file-name)
274           (if (string-contains file-name (ly:get-option 'datadir))
275               (begin
276                 (set! file-name (ly:string-substitute (ly:get-option 'datadir)
277                                                       "" file-name))
278                 (format #f
279                         "lilypond-datadir (~a) concatstrings (r) file .loadfont\n"
280                         file-name))
281               (format #f "(~a) (r) file .loadfont\n" file-name))
282           (format #f "% cannot find font file: ~a\n" file-name)))
283
284     (let* ((font (car font-name-filename))
285            (name (cadr font-name-filename))
286            (file-name (caddr font-name-filename))
287            (font-index (cadddr font-name-filename))
288            (bare-file-name (ly:find-file file-name)))
289       (cond
290        ((and (number? font-index)
291              (!= font-index 0))
292         (ly:warning (_ "Font ~a cannot be loaded via Ghostscript because its font-index (~a) is not zero.")
293                     name font-index)
294         (load-font font-name-filename))
295        ((and (string? bare-file-name)
296              (eq? (ly:get-font-format bare-file-name font-index) 'CFF)
297              (is-collection-font? bare-file-name))
298         (ly:warning (_ "Font ~a cannot be loaded via Ghostscript because it is an OpenType/CFF (OTC) font.")
299                     name)
300         (load-font font-name-filename))
301        ;; TODO: Check TrueType fonts that do not have glyph names.
302        (else
303         (cons name
304               (if (mac-font? bare-file-name)
305                   (handle-mac-font name bare-file-name)
306                   (cond
307                    ((and font (cff-font? font))
308                     (ps-load-file (ly:find-file
309                                    (format #f "~a.otf" file-name))))
310                    ((string? bare-file-name)
311                     (ps-load-file file-name))
312                    (else
313                     (ly:warning (_ "cannot embed ~S=~S") name file-name)
314                     ""))))))))
315
316   (define (dir-join a b)
317     (if (equal? a "")
318         b
319         (string-append a "/" b)))
320
321   (define (dir-listing dir-name)
322     (define (dir-helper dir lst)
323       (let ((e (readdir dir)))
324         (if (eof-object? e)
325             lst
326             (dir-helper dir (cons e lst)))))
327     (reverse (dir-helper (opendir dir-name) '())))
328
329   (define (handle-mac-font name file-name)
330     (let* ((dir-name (tmpnam))
331            (files '())
332            (status 0)
333            (embed #f)
334            (cwd (getcwd)))
335       (mkdir dir-name #o700)
336       (chdir dir-name)
337       (set! status (ly:system (list "fondu" "-force" file-name)))
338       (chdir cwd)
339       (set! files (dir-listing dir-name))
340       (for-each
341        (lambda (f)
342          (let* ((full-name (dir-join dir-name f)))
343            (if (and (not embed)
344                     (equal? 'regular (stat:type (stat full-name)))
345                     (equal? name (ly:ttf-ps-name full-name)))
346                (set! embed (font-file-as-ps-string name full-name 0)))
347            (if (or (equal? "." f)
348                    (equal? ".." f))
349                #t
350                (delete-file full-name))))
351        files)
352       (rmdir dir-name)
353       (if (not embed)
354           (begin
355             (set! embed "% failed\n")
356             (ly:warning (_ "cannot extract file matching ~a from ~a")
357                         name file-name)))
358       embed))
359
360   (define (font-file-as-ps-string name file-name font-index)
361     (let ((font-format (ly:get-font-format file-name font-index)))
362       (cond
363        ((eq? font-format (string->symbol "Type 1"))
364         ;; Type 1 (PFA and PFB) fonts
365         (ly:type1->pfa file-name))
366        ((eq? font-format 'TrueType)
367         ;; TrueType fonts (TTF) and TrueType Collection (TTC)
368         (ly:ttf->pfa file-name font-index))
369        ((eq? font-format 'CFF)
370         ;; OpenType/CFF fonts (OTF) and OpenType/CFF Collection (OTC)
371         (ps-embed-cff (ly:otf->cff file-name font-index) name 0))
372        (else
373         (ly:warning (_ "do not know how to embed ~S=~S") name file-name)
374         ""))))
375
376   (define (mac-font? bare-file-name)
377     (and (eq? PLATFORM 'darwin)
378          bare-file-name
379          (or (string-endswith bare-file-name ".dfont")
380              (= (stat:size (stat bare-file-name)) 0))))
381
382   (define (load-font font-psname-filename-fontindex)
383     (let* ((font (list-ref font-psname-filename-fontindex 0))
384            (name (list-ref font-psname-filename-fontindex 1))
385            (file-name (list-ref font-psname-filename-fontindex 2))
386            (font-index (list-ref font-psname-filename-fontindex 3))
387            (bare-file-name (ly:find-file file-name)))
388       (cons name
389             (cond ((mac-font? bare-file-name)
390                    (handle-mac-font name bare-file-name))
391                   ((and font (cff-font? font))
392                    (ps-embed-cff (ly:otf-font-table-data font "CFF ")
393                                  name
394                                  0))
395                   (bare-file-name (font-file-as-ps-string
396                                    name bare-file-name font-index))
397                   (else
398                    (ly:warning (_ "do not know how to embed font ~s ~s ~s")
399                                name file-name font))))))
400
401   (define (load-fonts paper)
402     (let* ((fonts (ly:paper-fonts paper))
403
404            ;; todo - doc format of list.
405            (all-font-names
406             (map
407              (lambda (font)
408                (cond ((string? (ly:font-file-name font))
409                       (list (list font
410                                   (ly:font-name font)
411                                   (ly:font-file-name font)
412                                   #f)))
413                      ((ly:pango-font? font)
414                       (map (lambda (psname-filename-fontindex)
415                              (list #f
416                                    (list-ref psname-filename-fontindex 0)
417                                    (list-ref psname-filename-fontindex 1)
418                                    (list-ref psname-filename-fontindex 2)))
419                            (ly:pango-font-physical-fonts font)))
420                      (else
421                       (ly:font-sub-fonts font))))
422              fonts))
423            (font-names (uniq-list
424                         (sort (concatenate all-font-names)
425                               (lambda (x y) (string<? (cadr x) (cadr y))))))
426
427            ;; slightly spaghetti-ish: deciding what to load where
428            ;; is smeared out.
429            (font-loader
430             (lambda (name)
431               (cond ((ly:get-option 'gs-load-fonts)
432                      (load-font-via-GS name))
433                     ((ly:get-option 'gs-load-lily-fonts)
434                      (if (or (string-contains (caddr name)
435                                               (ly:get-option 'datadir))
436                              (internal-font? name))
437                          (load-font-via-GS name)
438                          (load-font name)))
439                     (else
440                      (load-font name)))))
441            (pfas (map font-loader font-names)))
442       pfas))
443
444
445   (display "%%BeginProlog\n" port)
446   (format
447    port
448    "/lilypond-datadir where {pop} {userdict /lilypond-datadir (~a) put } ifelse"
449    (ly:get-option 'datadir))
450   (if load-fonts?
451       (for-each (lambda (f)
452                   (format port "\n%%BeginFont: ~a\n" (car f))
453                   (display (cdr f) port)
454                   (display "%%EndFont\n" port))
455                 (load-fonts paper)))
456   (if (ly:bigpdfs)
457       (display (procset "encodingdefs.ps") port))
458   (display (setup-variables paper) port)
459
460   ;; adobe note 5002: should initialize variables before loading routines.
461   (display (procset "music-drawing-routines.ps") port)
462   (display (procset "lilyponddefs.ps") port)
463   (display "%%EndProlog\n" port)
464   (display "%%BeginSetup\ninit-lilypond-parameters\n%%EndSetup\n\n" port))
465
466 (define (ps-quote str)
467   (fold
468    (lambda (replacement-list result)
469      (string-join
470       (string-split
471        result
472        (car replacement-list))
473       (cadr replacement-list)))
474    str
475    '((#\\ "\\\\") (#\( "\\(") (#\) "\\)"))))
476
477 ;;; Create DOCINFO pdfmark containing metadata
478 ;;; header fields with pdf prefix override those without the prefix
479 (define (handle-metadata header port)
480   (define (metadata-encode val)
481     ;; First, call ly:encode-string-for-pdf to encode the string (latin1 or
482     ;; utf-16be), then escape all parentheses and backslashes
483     ;; FIXME guile-2.0: use (string->utf16 str 'big) instead
484
485     (ps-quote (ly:encode-string-for-pdf val)))
486   (define (metadata-lookup-output overridevar fallbackvar field)
487     (let* ((overrideval (ly:modules-lookup (list header) overridevar))
488            (fallbackval (ly:modules-lookup (list header) fallbackvar))
489            (val (if overrideval overrideval fallbackval)))
490       (if val
491           (format port "/~a (~a)\n" field (metadata-encode (markup->string val (list header)))))))
492
493   (if (module? header)
494       (begin
495        (display "mark " port)
496        (metadata-lookup-output 'pdfauthor 'author "Author")
497        (format port "/Creator (LilyPond ~a)\n" (lilypond-version))
498        (metadata-lookup-output 'pdftitle 'title "Title")
499        (metadata-lookup-output 'pdfsubject 'subject "Subject")
500        (metadata-lookup-output 'pdfkeywords 'keywords "Keywords")
501        (metadata-lookup-output 'pdfmodDate 'modDate "ModDate")
502        (metadata-lookup-output 'pdfsubtitle 'subtitle "Subtitle")
503        (metadata-lookup-output 'pdfcomposer 'composer "Composer")
504        (metadata-lookup-output 'pdfarranger 'arranger "Arranger")
505        (metadata-lookup-output 'pdfpoet 'poet "Poet")
506        (metadata-lookup-output 'pdfcopyright 'copyright "Copyright")
507        (display "/DOCINFO pdfmark\n\n" port)))
508
509   (if (ly:get-option 'embed-source-code)
510       (let ((source-list (delete-duplicates
511                           (remove (lambda (str)
512                                     (or
513                                      (string-contains str
514                                        (ly:get-option 'datadir))
515                                      (string=? str
516                                        "<included string>")))
517                             (ly:source-files)))))
518          (display "\n/pdfmark where
519 {pop} {userdict /pdfmark /cleartomark load put} ifelse" port)
520          (for-each (lambda (fname idx)
521                      (format port "\n
522 mark /_objdef {ly~a_stream} /type /stream   /OBJ pdfmark
523 mark {ly~a_stream} << /Type /EmbeddedFile>> /PUT pdfmark
524 mark {ly~a_stream} (~a) /PUT pdfmark
525 mark /Name (LilyPond source file ~a)
526 /FS << /Type /Filespec /F (~a) /EF << /F {ly~a_stream} >> >> /EMBED pdfmark
527 mark {ly~a_stream} /CLOSE pdfmark
528 \n"
529                 idx idx idx
530                 (ps-quote (ly:gulp-file fname))
531                   idx fname idx idx))
532           source-list (iota (length source-list))))))
533
534 (define-public (output-framework basename book scopes fields)
535   (let* ((port-tmp (make-tmpfile))
536          (tmp-name (port-filename port-tmp))
537          (outputter (ly:make-paper-outputter
538                      port-tmp
539                      'ps))
540          (paper (ly:paper-book-paper book))
541          (header (ly:paper-book-header book))
542          (systems (ly:paper-book-systems book))
543          (page-stencils (map page-stencil (ly:paper-book-pages book)))
544          (landscape? (eq? (ly:output-def-lookup paper 'landscape) #t))
545          (page-number (1- (ly:output-def-lookup paper 'first-page-number)))
546          (page-count (length page-stencils))
547          (port (ly:outputter-port outputter)))
548     (if (ly:get-option 'clip-systems)
549         (clip-system-EPSes basename book))
550     (if (ly:get-option 'dump-signatures)
551         (write-system-signatures basename (ly:paper-book-systems book) 1))
552     (output-scopes scopes fields basename)
553     (display (file-header paper page-count #t) port)
554     ;; don't do BeginDefaults PageMedia: A4
555     ;; not necessary and wrong
556     (write-preamble paper #t port)
557     (handle-metadata header port)
558     (for-each
559      (lambda (page)
560        (set! page-number (1+ page-number))
561        (dump-page outputter page page-number page-count landscape?))
562      page-stencils)
563     (display "%%Trailer\n%%EOF\n" port)
564     (ly:outputter-close outputter)
565     (postprocess-output book framework-ps-module (ly:output-formats)
566                         basename tmp-name #f)))
567
568 (define-public (dump-stencil-as-EPS paper dump-me filename
569                                     load-fonts)
570   (let* ((xext (ly:stencil-extent dump-me X))
571          (yext (ly:stencil-extent dump-me Y))
572          (padding (ly:get-option 'eps-box-padding))
573          (left-overshoot (if (number? padding)
574                              (* -1 padding (ly:output-def-lookup paper 'mm))
575                              #f))
576          (bbox
577           (map
578            (lambda (x)
579              (if (or (nan? x) (inf? x)
580                      ;; FIXME: huh?
581                      (equal? (format #f "~S" x) "+#.#")
582                      (equal? (format #f "~S" x) "-#.#"))
583                  0.0 x))
584
585            ;; the left-overshoot is to make sure that
586            ;; bar numbers stick out of margin uniformly.
587            ;;
588            (list
589             (if (number? left-overshoot)
590                 (min left-overshoot (car xext))
591                 (car xext))
592             (car yext) (cdr xext) (cdr yext)))))
593     (dump-stencil-as-EPS-with-bbox paper dump-me filename load-fonts bbox)))
594
595 (define-public (dump-stencil-as-EPS-with-bbox paper dump-me filename
596                                               load-fonts
597                                               bbox)
598   "Create an EPS file from stencil @var{dump-me} to @var{filename}.
599 @var{bbox} has format @code{(left-x, lower-y, right-x, upper-y)}.  If
600 @var{load-fonts} set, include fonts inline."
601   (define (to-rounded-bp-box box)
602     "Convert box to 1/72 inch with rounding to enlarge the box."
603     (let* ((scale (ly:output-def-lookup paper 'output-scale))
604            (strip-non-number (lambda (x)
605                                (if (or (nan? x)
606                                        (inf? x))
607                                    0.0
608                                    x)))
609            (directed-round (lambda (x rounder)
610                              (inexact->exact
611                               (rounder (/ (* (strip-non-number x) scale)
612                                           (ly:bp 1)))))))
613       (list (directed-round (car box) floor)
614             (directed-round (cadr box) floor)
615             (directed-round (max (1+ (car box)) (caddr box)) ceiling)
616             (directed-round (max (1+ (cadr box)) (cadddr box)) ceiling))))
617
618   (let* ((outputter (ly:make-paper-outputter
619                      ;; FIXME: better wrap open/open-file,
620                      ;; content-mangling is always bad.
621                      ;; MINGW hack: need to have "b"inary for embedding CFFs
622                      (open-file (format #f "~a.eps" filename) "wb")
623                      'ps))
624          (port (ly:outputter-port outputter))
625          (rounded-bbox (to-rounded-bp-box bbox))
626          (port (ly:outputter-port outputter))
627          (header (eps-header paper rounded-bbox load-fonts)))
628     (display header port)
629     (write-preamble paper load-fonts port)
630     (display "/mark_page_link { pop pop pop pop pop } bind def\n" port)
631     (display "gsave set-ps-scale-to-lily-scale\n" port)
632     (display "/helpEmmentaler-Brace where {pop helpEmmentaler-Brace} if\n" port)
633     (display "/helpEmmentaler-11 where {pop helpEmmentaler-11} if\n" port)
634     (display "/helpEmmentaler-13 where {pop helpEmmentaler-13} if\n" port)
635     (display "/helpEmmentaler-14 where {pop helpEmmentaler-14} if\n" port)
636     (display "/helpEmmentaler-16 where {pop helpEmmentaler-16} if\n" port)
637     (display "/helpEmmentaler-18 where {pop helpEmmentaler-18} if\n" port)
638     (display "/helpEmmentaler-20 where {pop helpEmmentaler-20} if\n" port)
639     (display "/helpEmmentaler-23 where {pop helpEmmentaler-23} if\n" port)
640     (display "/helpEmmentaler-26 where {pop helpEmmentaler-26} if\n" port)
641     (ly:outputter-dump-stencil outputter dump-me)
642     (display "stroke grestore\n%%Trailer\n%%EOF\n" port)
643     (ly:outputter-close outputter)))
644
645 (define (clip-systems-to-region basename paper systems region do-pdf do-png)
646   (let* ((extents-system-pairs
647           (filtered-map (lambda (paper-system)
648                           (let* ((x-ext (system-clipped-x-extent
649                                          (paper-system-system-grob paper-system)
650                                          region)))
651                             (if x-ext
652                                 (cons x-ext paper-system)
653                                 #f)))
654                         systems))
655          (count 0))
656     (for-each
657      (lambda (ext-system-pair)
658        (let* ((xext (car ext-system-pair))
659               (paper-system (cdr ext-system-pair))
660               (yext (paper-system-extent paper-system Y))
661               (bbox (list (car xext) (car yext)
662                           (cdr xext) (cdr yext)))
663               (filename (if (< 0 count)
664                             (format #f "~a-~a" basename count)
665                             basename)))
666          (set! count (1+ count))
667          (dump-stencil-as-EPS-with-bbox paper
668                                         (paper-system-stencil paper-system)
669                                         filename
670                                         (ly:get-option 'include-eps-fonts)
671                                         bbox)
672          (if do-pdf
673              (postscript->pdf 0 0 filename (format #f "~a.eps" filename) #t))
674          (if do-png
675              (postscript->png (ly:get-option 'resolution) 0 0
676                               filename (format #f "~a.eps" filename) #t))))
677      extents-system-pairs)))
678
679 (define-public (clip-system-EPSes basename paper-book)
680   (define do-pdf
681     (member "pdf" (ly:output-formats)))
682   (define do-png
683     (member "png" (ly:output-formats)))
684
685   (define (clip-score-systems basename systems)
686     (let* ((layout (ly:grob-layout (paper-system-system-grob (car systems))))
687            (regions (ly:output-def-lookup layout 'clip-regions)))
688       (for-each
689        (lambda (region)
690          (clip-systems-to-region
691           (format #f "~a-from-~a-to-~a-clip"
692                   basename
693                   (rhythmic-location->file-string (car region))
694                   (rhythmic-location->file-string (cdr region)))
695           layout systems region
696           do-pdf do-png))
697        regions)))
698
699   ;; partition in system lists sharing their layout blocks
700   (let* ((systems (ly:paper-book-systems paper-book))
701          (count 0)
702          (score-system-list '()))
703     (fold
704      (lambda (system last-system)
705        (if (not (and last-system
706                      (equal? (paper-system-layout last-system)
707                              (paper-system-layout system))))
708            (set! score-system-list (cons '() score-system-list)))
709        (if (paper-system-layout system)
710            (set-car! score-system-list (cons system (car score-system-list))))
711        ;; pass value.
712        system)
713      #f
714      systems)
715     (for-each (lambda (system-list)
716                 ;; filter out headers and top-level markup
717                 (if (pair? system-list)
718                     (clip-score-systems
719                      (if (> count 0)
720                          (format #f "~a-~a" basename count)
721                          basename)
722                      system-list)))
723               score-system-list)))
724
725 (define-public (output-preview-framework basename book scopes fields)
726   (let* ((paper (ly:paper-book-paper book))
727          (systems (relevant-book-systems book))
728          (to-dump-systems (relevant-dump-systems systems)))
729     (dump-stencil-as-EPS paper
730                          (stack-stencils Y DOWN 0.0
731                                          (map paper-system-stencil
732                                               (reverse to-dump-systems)))
733                          (format #f "~a.preview" basename)
734                          #t)
735     (postprocess-output book framework-ps-module
736                         (cons "png" (ly:output-formats))
737                         (format #f "~a.preview" basename)
738                         (format #f "~a.preview.eps" basename)
739                         #t
740                         )))
741
742 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
743
744 (define (output-width-height defs)
745   (let* ((landscape (ly:output-def-lookup defs 'landscape))
746          (output-scale (ly:output-def-lookup defs 'output-scale))
747          (convert (lambda (x)
748                     (* x output-scale (/ (ly:bp 1)))))
749          (paper-width (convert (ly:output-def-lookup defs 'paper-width)))
750          (paper-height (convert (ly:output-def-lookup defs 'paper-height)))
751          (w (if landscape paper-height paper-width))
752          (h (if landscape paper-width paper-height)))
753     (cons w h)))
754
755 (define (output-resolution defs)
756   (let ((defs-resolution (ly:output-def-lookup defs 'pngresolution)))
757     (if (number? defs-resolution)
758         defs-resolution
759         (ly:get-option 'resolution))))
760
761 (define-public (convert-to-pdf book base-name tmp-name is-eps)
762   (let* ((defs (ly:paper-book-paper book))
763          (width-height (output-width-height defs))
764          (width (car width-height))
765          (height (cdr width-height)))
766     (postscript->pdf width height base-name tmp-name is-eps)))
767
768 (define-public (convert-to-png book base-name tmp-name is-eps)
769   (let* ((defs (ly:paper-book-paper book))
770          (resolution (output-resolution defs))
771          (width-height (output-width-height defs))
772          (width (car width-height))
773          (height (cdr width-height)))
774     (postscript->png resolution width height base-name tmp-name is-eps)))
775
776 (define-public (convert-to-ps book base-name tmp-name is-eps)
777   (postscript->ps base-name tmp-name is-eps))
778
779 (define-public (output-classic-framework basename book scopes fields)
780   (ly:error (_ "\nThe PostScript backend does not support the
781 system-by-system output.  For that, use the EPS backend instead,
782
783   lilypond -dbackend=eps FILE
784
785 If you have cut & pasted a lilypond fragment from a webpage, be sure
786 to only remove anything before
787
788   %% ****************************************************************
789   %% Start cut-&-pastable-section
790   %% ****************************************************************
791 ")))