]> git.donarmstrong.com Git - lilypond.git/blob - scm/framework-ps.scm
Issue 4900: Improve `-dgs-load-fonts` option for non-zero font-index
[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 (ps-load-file file-name)
261       (if (string? file-name)
262           (if (string-contains file-name (ly:get-option 'datadir))
263               (begin
264                 (set! file-name (ly:string-substitute (ly:get-option 'datadir)
265                                                       "" file-name))
266                 (format #f
267                         "lilypond-datadir (~a) concatstrings (r) file .loadfont\n"
268                         file-name))
269               (format #f "(~a) (r) file .loadfont\n" file-name))
270           (format #f "% cannot find font file: ~a\n" file-name)))
271
272     (let* ((font (car font-name-filename))
273            (name (cadr font-name-filename))
274            (file-name (caddr font-name-filename))
275            (font-index (cadddr font-name-filename))
276            (bare-file-name (ly:find-file file-name)))
277       (cond
278        ((and (number? font-index)
279              (!= font-index 0))
280         (ly:warning (_ "Font ~a cannot be loaded via Ghostscript because its font-index (~a) is not zero.")
281                     name font-index)
282         (load-font font-name-filename))
283        ;; TODO: Check OTC fonts.
284        ;; TODO: Check TrueType fonts that do not have glyph names.
285        (else
286         (cons name
287               (if (mac-font? bare-file-name)
288                   (handle-mac-font name bare-file-name)
289                   (cond
290                    ((and font (cff-font? font))
291                     (ps-load-file (ly:find-file
292                                    (format #f "~a.otf" file-name))))
293                    ((string? bare-file-name)
294                     (ps-load-file file-name))
295                    (else
296                     (ly:warning (_ "cannot embed ~S=~S") name file-name)
297                     ""))))))))
298
299   (define (dir-join a b)
300     (if (equal? a "")
301         b
302         (string-append a "/" b)))
303
304   (define (dir-listing dir-name)
305     (define (dir-helper dir lst)
306       (let ((e (readdir dir)))
307         (if (eof-object? e)
308             lst
309             (dir-helper dir (cons e lst)))))
310     (reverse (dir-helper (opendir dir-name) '())))
311
312   (define (handle-mac-font name file-name)
313     (let* ((dir-name (tmpnam))
314            (files '())
315            (status 0)
316            (embed #f)
317            (cwd (getcwd)))
318       (mkdir dir-name #o700)
319       (chdir dir-name)
320       (set! status (ly:system (list "fondu" "-force" file-name)))
321       (chdir cwd)
322       (set! files (dir-listing dir-name))
323       (for-each
324        (lambda (f)
325          (let* ((full-name (dir-join dir-name f)))
326            (if (and (not embed)
327                     (equal? 'regular (stat:type (stat full-name)))
328                     (equal? name (ly:ttf-ps-name full-name)))
329                (set! embed (font-file-as-ps-string name full-name 0)))
330            (if (or (equal? "." f)
331                    (equal? ".." f))
332                #t
333                (delete-file full-name))))
334        files)
335       (rmdir dir-name)
336       (if (not embed)
337           (begin
338             (set! embed "% failed\n")
339             (ly:warning (_ "cannot extract file matching ~a from ~a")
340                         name file-name)))
341       embed))
342
343   (define (font-file-as-ps-string name file-name font-index)
344     (let ((font-format (ly:get-font-format file-name font-index)))
345       (cond
346        ((eq? font-format (string->symbol "Type 1"))
347         ;; Type 1 (PFA and PFB) fonts
348         (ly:type1->pfa file-name))
349        ((eq? font-format 'TrueType)
350         ;; TrueType fonts (TTF) and TrueType Collection (TTC)
351         (ly:ttf->pfa file-name font-index))
352        ((eq? font-format 'CFF)
353         ;; OpenType/CFF fonts (OTF) and OpenType/CFF Collection (OTC)
354         (ps-embed-cff (ly:otf->cff file-name font-index) name 0))
355        (else
356         (ly:warning (_ "do not know how to embed ~S=~S") name file-name)
357         ""))))
358
359   (define (mac-font? bare-file-name)
360     (and (eq? PLATFORM 'darwin)
361          bare-file-name
362          (or (string-endswith bare-file-name ".dfont")
363              (= (stat:size (stat bare-file-name)) 0))))
364
365   (define (load-font font-psname-filename-fontindex)
366     (let* ((font (list-ref font-psname-filename-fontindex 0))
367            (name (list-ref font-psname-filename-fontindex 1))
368            (file-name (list-ref font-psname-filename-fontindex 2))
369            (font-index (list-ref font-psname-filename-fontindex 3))
370            (bare-file-name (ly:find-file file-name)))
371       (cons name
372             (cond ((mac-font? bare-file-name)
373                    (handle-mac-font name bare-file-name))
374                   ((and font (cff-font? font))
375                    (ps-embed-cff (ly:otf-font-table-data font "CFF ")
376                                  name
377                                  0))
378                   (bare-file-name (font-file-as-ps-string
379                                    name bare-file-name font-index))
380                   (else
381                    (ly:warning (_ "do not know how to embed font ~s ~s ~s")
382                                name file-name font))))))
383
384   (define (load-fonts paper)
385     (let* ((fonts (ly:paper-fonts paper))
386
387            ;; todo - doc format of list.
388            (all-font-names
389             (map
390              (lambda (font)
391                (cond ((string? (ly:font-file-name font))
392                       (list (list font
393                                   (ly:font-name font)
394                                   (ly:font-file-name font)
395                                   #f)))
396                      ((ly:pango-font? font)
397                       (map (lambda (psname-filename-fontindex)
398                              (list #f
399                                    (list-ref psname-filename-fontindex 0)
400                                    (list-ref psname-filename-fontindex 1)
401                                    (list-ref psname-filename-fontindex 2)))
402                            (ly:pango-font-physical-fonts font)))
403                      (else
404                       (ly:font-sub-fonts font))))
405              fonts))
406            (font-names (uniq-list
407                         (sort (concatenate all-font-names)
408                               (lambda (x y) (string<? (cadr x) (cadr y))))))
409
410            ;; slightly spaghetti-ish: deciding what to load where
411            ;; is smeared out.
412            (font-loader
413             (lambda (name)
414               (cond ((ly:get-option 'gs-load-fonts)
415                      (load-font-via-GS name))
416                     ((ly:get-option 'gs-load-lily-fonts)
417                      (if (or (string-contains (caddr name)
418                                               (ly:get-option 'datadir))
419                              (internal-font? name))
420                          (load-font-via-GS name)
421                          (load-font name)))
422                     (else
423                      (load-font name)))))
424            (pfas (map font-loader font-names)))
425       pfas))
426
427
428   (display "%%BeginProlog\n" port)
429   (format
430    port
431    "/lilypond-datadir where {pop} {userdict /lilypond-datadir (~a) put } ifelse"
432    (ly:get-option 'datadir))
433   (if load-fonts?
434       (for-each (lambda (f)
435                   (format port "\n%%BeginFont: ~a\n" (car f))
436                   (display (cdr f) port)
437                   (display "%%EndFont\n" port))
438                 (load-fonts paper)))
439   (if (ly:bigpdfs)
440       (display (procset "encodingdefs.ps") port))
441   (display (setup-variables paper) port)
442
443   ;; adobe note 5002: should initialize variables before loading routines.
444   (display (procset "music-drawing-routines.ps") port)
445   (display (procset "lilyponddefs.ps") port)
446   (display "%%EndProlog\n" port)
447   (display "%%BeginSetup\ninit-lilypond-parameters\n%%EndSetup\n\n" port))
448
449 (define (ps-quote str)
450   (fold
451    (lambda (replacement-list result)
452      (string-join
453       (string-split
454        result
455        (car replacement-list))
456       (cadr replacement-list)))
457    str
458    '((#\\ "\\\\") (#\( "\\(") (#\) "\\)"))))
459
460 ;;; Create DOCINFO pdfmark containing metadata
461 ;;; header fields with pdf prefix override those without the prefix
462 (define (handle-metadata header port)
463   (define (metadata-encode val)
464     ;; First, call ly:encode-string-for-pdf to encode the string (latin1 or
465     ;; utf-16be), then escape all parentheses and backslashes
466     ;; FIXME guile-2.0: use (string->utf16 str 'big) instead
467
468     (ps-quote (ly:encode-string-for-pdf val)))
469   (define (metadata-lookup-output overridevar fallbackvar field)
470     (let* ((overrideval (ly:modules-lookup (list header) overridevar))
471            (fallbackval (ly:modules-lookup (list header) fallbackvar))
472            (val (if overrideval overrideval fallbackval)))
473       (if val
474           (format port "/~a (~a)\n" field (metadata-encode (markup->string val (list header)))))))
475
476   (if (module? header)
477       (begin
478        (display "mark " port)
479        (metadata-lookup-output 'pdfauthor 'author "Author")
480        (format port "/Creator (LilyPond ~a)\n" (lilypond-version))
481        (metadata-lookup-output 'pdftitle 'title "Title")
482        (metadata-lookup-output 'pdfsubject 'subject "Subject")
483        (metadata-lookup-output 'pdfkeywords 'keywords "Keywords")
484        (metadata-lookup-output 'pdfmodDate 'modDate "ModDate")
485        (metadata-lookup-output 'pdfsubtitle 'subtitle "Subtitle")
486        (metadata-lookup-output 'pdfcomposer 'composer "Composer")
487        (metadata-lookup-output 'pdfarranger 'arranger "Arranger")
488        (metadata-lookup-output 'pdfpoet 'poet "Poet")
489        (metadata-lookup-output 'pdfcopyright 'copyright "Copyright")
490        (display "/DOCINFO pdfmark\n\n" port)))
491
492   (if (ly:get-option 'embed-source-code)
493       (let ((source-list (delete-duplicates
494                           (remove (lambda (str)
495                                     (or
496                                      (string-contains str
497                                        (ly:get-option 'datadir))
498                                      (string=? str
499                                        "<included string>")))
500                             (ly:source-files)))))
501          (display "\n/pdfmark where
502 {pop} {userdict /pdfmark /cleartomark load put} ifelse" port)
503          (for-each (lambda (fname idx)
504                      (format port "\n
505 mark /_objdef {ly~a_stream} /type /stream   /OBJ pdfmark
506 mark {ly~a_stream} << /Type /EmbeddedFile>> /PUT pdfmark
507 mark {ly~a_stream} (~a) /PUT pdfmark
508 mark /Name (LilyPond source file ~a)
509 /FS << /Type /Filespec /F (~a) /EF << /F {ly~a_stream} >> >> /EMBED pdfmark
510 mark {ly~a_stream} /CLOSE pdfmark
511 \n"
512                 idx idx idx
513                 (ps-quote (ly:gulp-file fname))
514                   idx fname idx idx))
515           source-list (iota (length source-list))))))
516
517 (define-public (output-framework basename book scopes fields)
518   (let* ((port-tmp (make-tmpfile))
519          (tmp-name (port-filename port-tmp))
520          (outputter (ly:make-paper-outputter
521                      port-tmp
522                      'ps))
523          (paper (ly:paper-book-paper book))
524          (header (ly:paper-book-header book))
525          (systems (ly:paper-book-systems book))
526          (page-stencils (map page-stencil (ly:paper-book-pages book)))
527          (landscape? (eq? (ly:output-def-lookup paper 'landscape) #t))
528          (page-number (1- (ly:output-def-lookup paper 'first-page-number)))
529          (page-count (length page-stencils))
530          (port (ly:outputter-port outputter)))
531     (if (ly:get-option 'clip-systems)
532         (clip-system-EPSes basename book))
533     (if (ly:get-option 'dump-signatures)
534         (write-system-signatures basename (ly:paper-book-systems book) 1))
535     (output-scopes scopes fields basename)
536     (display (file-header paper page-count #t) port)
537     ;; don't do BeginDefaults PageMedia: A4
538     ;; not necessary and wrong
539     (write-preamble paper #t port)
540     (handle-metadata header port)
541     (for-each
542      (lambda (page)
543        (set! page-number (1+ page-number))
544        (dump-page outputter page page-number page-count landscape?))
545      page-stencils)
546     (display "%%Trailer\n%%EOF\n" port)
547     (ly:outputter-close outputter)
548     (postprocess-output book framework-ps-module (ly:output-formats)
549                         basename tmp-name #f)))
550
551 (define-public (dump-stencil-as-EPS paper dump-me filename
552                                     load-fonts)
553   (let* ((xext (ly:stencil-extent dump-me X))
554          (yext (ly:stencil-extent dump-me Y))
555          (padding (ly:get-option 'eps-box-padding))
556          (left-overshoot (if (number? padding)
557                              (* -1 padding (ly:output-def-lookup paper 'mm))
558                              #f))
559          (bbox
560           (map
561            (lambda (x)
562              (if (or (nan? x) (inf? x)
563                      ;; FIXME: huh?
564                      (equal? (format #f "~S" x) "+#.#")
565                      (equal? (format #f "~S" x) "-#.#"))
566                  0.0 x))
567
568            ;; the left-overshoot is to make sure that
569            ;; bar numbers stick out of margin uniformly.
570            ;;
571            (list
572             (if (number? left-overshoot)
573                 (min left-overshoot (car xext))
574                 (car xext))
575             (car yext) (cdr xext) (cdr yext)))))
576     (dump-stencil-as-EPS-with-bbox paper dump-me filename load-fonts bbox)))
577
578 (define-public (dump-stencil-as-EPS-with-bbox paper dump-me filename
579                                               load-fonts
580                                               bbox)
581   "Create an EPS file from stencil @var{dump-me} to @var{filename}.
582 @var{bbox} has format @code{(left-x, lower-y, right-x, upper-y)}.  If
583 @var{load-fonts} set, include fonts inline."
584   (define (to-rounded-bp-box box)
585     "Convert box to 1/72 inch with rounding to enlarge the box."
586     (let* ((scale (ly:output-def-lookup paper 'output-scale))
587            (strip-non-number (lambda (x)
588                                (if (or (nan? x)
589                                        (inf? x))
590                                    0.0
591                                    x)))
592            (directed-round (lambda (x rounder)
593                              (inexact->exact
594                               (rounder (/ (* (strip-non-number x) scale)
595                                           (ly:bp 1)))))))
596       (list (directed-round (car box) floor)
597             (directed-round (cadr box) floor)
598             (directed-round (max (1+ (car box)) (caddr box)) ceiling)
599             (directed-round (max (1+ (cadr box)) (cadddr box)) ceiling))))
600
601   (let* ((outputter (ly:make-paper-outputter
602                      ;; FIXME: better wrap open/open-file,
603                      ;; content-mangling is always bad.
604                      ;; MINGW hack: need to have "b"inary for embedding CFFs
605                      (open-file (format #f "~a.eps" filename) "wb")
606                      'ps))
607          (port (ly:outputter-port outputter))
608          (rounded-bbox (to-rounded-bp-box bbox))
609          (port (ly:outputter-port outputter))
610          (header (eps-header paper rounded-bbox load-fonts)))
611     (display header port)
612     (write-preamble paper load-fonts port)
613     (display "/mark_page_link { pop pop pop pop pop } bind def\n" port)
614     (display "gsave set-ps-scale-to-lily-scale\n" port)
615     (display "/helpEmmentaler-Brace where {pop helpEmmentaler-Brace} if\n" port)
616     (display "/helpEmmentaler-11 where {pop helpEmmentaler-11} if\n" port)
617     (display "/helpEmmentaler-13 where {pop helpEmmentaler-13} if\n" port)
618     (display "/helpEmmentaler-14 where {pop helpEmmentaler-14} if\n" port)
619     (display "/helpEmmentaler-16 where {pop helpEmmentaler-16} if\n" port)
620     (display "/helpEmmentaler-18 where {pop helpEmmentaler-18} if\n" port)
621     (display "/helpEmmentaler-20 where {pop helpEmmentaler-20} if\n" port)
622     (display "/helpEmmentaler-23 where {pop helpEmmentaler-23} if\n" port)
623     (display "/helpEmmentaler-26 where {pop helpEmmentaler-26} if\n" port)
624     (ly:outputter-dump-stencil outputter dump-me)
625     (display "stroke grestore\n%%Trailer\n%%EOF\n" port)
626     (ly:outputter-close outputter)))
627
628 (define (clip-systems-to-region basename paper systems region do-pdf do-png)
629   (let* ((extents-system-pairs
630           (filtered-map (lambda (paper-system)
631                           (let* ((x-ext (system-clipped-x-extent
632                                          (paper-system-system-grob paper-system)
633                                          region)))
634                             (if x-ext
635                                 (cons x-ext paper-system)
636                                 #f)))
637                         systems))
638          (count 0))
639     (for-each
640      (lambda (ext-system-pair)
641        (let* ((xext (car ext-system-pair))
642               (paper-system (cdr ext-system-pair))
643               (yext (paper-system-extent paper-system Y))
644               (bbox (list (car xext) (car yext)
645                           (cdr xext) (cdr yext)))
646               (filename (if (< 0 count)
647                             (format #f "~a-~a" basename count)
648                             basename)))
649          (set! count (1+ count))
650          (dump-stencil-as-EPS-with-bbox paper
651                                         (paper-system-stencil paper-system)
652                                         filename
653                                         (ly:get-option 'include-eps-fonts)
654                                         bbox)
655          (if do-pdf
656              (postscript->pdf 0 0 filename (format #f "~a.eps" filename) #t))
657          (if do-png
658              (postscript->png (ly:get-option 'resolution) 0 0
659                               filename (format #f "~a.eps" filename) #t))))
660      extents-system-pairs)))
661
662 (define-public (clip-system-EPSes basename paper-book)
663   (define do-pdf
664     (member "pdf" (ly:output-formats)))
665   (define do-png
666     (member "png" (ly:output-formats)))
667
668   (define (clip-score-systems basename systems)
669     (let* ((layout (ly:grob-layout (paper-system-system-grob (car systems))))
670            (regions (ly:output-def-lookup layout 'clip-regions)))
671       (for-each
672        (lambda (region)
673          (clip-systems-to-region
674           (format #f "~a-from-~a-to-~a-clip"
675                   basename
676                   (rhythmic-location->file-string (car region))
677                   (rhythmic-location->file-string (cdr region)))
678           layout systems region
679           do-pdf do-png))
680        regions)))
681
682   ;; partition in system lists sharing their layout blocks
683   (let* ((systems (ly:paper-book-systems paper-book))
684          (count 0)
685          (score-system-list '()))
686     (fold
687      (lambda (system last-system)
688        (if (not (and last-system
689                      (equal? (paper-system-layout last-system)
690                              (paper-system-layout system))))
691            (set! score-system-list (cons '() score-system-list)))
692        (if (paper-system-layout system)
693            (set-car! score-system-list (cons system (car score-system-list))))
694        ;; pass value.
695        system)
696      #f
697      systems)
698     (for-each (lambda (system-list)
699                 ;; filter out headers and top-level markup
700                 (if (pair? system-list)
701                     (clip-score-systems
702                      (if (> count 0)
703                          (format #f "~a-~a" basename count)
704                          basename)
705                      system-list)))
706               score-system-list)))
707
708 (define-public (output-preview-framework basename book scopes fields)
709   (let* ((paper (ly:paper-book-paper book))
710          (systems (relevant-book-systems book))
711          (to-dump-systems (relevant-dump-systems systems)))
712     (dump-stencil-as-EPS paper
713                          (stack-stencils Y DOWN 0.0
714                                          (map paper-system-stencil
715                                               (reverse to-dump-systems)))
716                          (format #f "~a.preview" basename)
717                          #t)
718     (postprocess-output book framework-ps-module
719                         (cons "png" (ly:output-formats))
720                         (format #f "~a.preview" basename)
721                         (format #f "~a.preview.eps" basename)
722                         #t
723                         )))
724
725 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
726
727 (define (output-width-height defs)
728   (let* ((landscape (ly:output-def-lookup defs 'landscape))
729          (output-scale (ly:output-def-lookup defs 'output-scale))
730          (convert (lambda (x)
731                     (* x output-scale (/ (ly:bp 1)))))
732          (paper-width (convert (ly:output-def-lookup defs 'paper-width)))
733          (paper-height (convert (ly:output-def-lookup defs 'paper-height)))
734          (w (if landscape paper-height paper-width))
735          (h (if landscape paper-width paper-height)))
736     (cons w h)))
737
738 (define (output-resolution defs)
739   (let ((defs-resolution (ly:output-def-lookup defs 'pngresolution)))
740     (if (number? defs-resolution)
741         defs-resolution
742         (ly:get-option 'resolution))))
743
744 (define-public (convert-to-pdf book base-name tmp-name is-eps)
745   (let* ((defs (ly:paper-book-paper book))
746          (width-height (output-width-height defs))
747          (width (car width-height))
748          (height (cdr width-height)))
749     (postscript->pdf width height base-name tmp-name is-eps)))
750
751 (define-public (convert-to-png book base-name tmp-name is-eps)
752   (let* ((defs (ly:paper-book-paper book))
753          (resolution (output-resolution defs))
754          (width-height (output-width-height defs))
755          (width (car width-height))
756          (height (cdr width-height)))
757     (postscript->png resolution width height base-name tmp-name is-eps)))
758
759 (define-public (convert-to-ps book base-name tmp-name is-eps)
760   (postscript->ps base-name tmp-name is-eps))
761
762 (define-public (output-classic-framework basename book scopes fields)
763   (ly:error (_ "\nThe PostScript backend does not support the
764 system-by-system output.  For that, use the EPS backend instead,
765
766   lilypond -dbackend=eps FILE
767
768 If you have cut & pasted a lilypond fragment from a webpage, be sure
769 to only remove anything before
770
771   %% ****************************************************************
772   %% Start cut-&-pastable-section
773   %% ****************************************************************
774 ")))