]> git.donarmstrong.com Git - lilypond.git/blob - scm/framework-ps.scm
Imported Upstream version 2.19.51
[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 never-embed-font-list (list))
218
219 (define (cff-font? font)
220   (let* ((cff-string (ly:otf-font-table-data font "CFF ")))
221     (> (string-length cff-string) 0)))
222
223 (define-public (ps-embed-cff body font-set-name version)
224   (let* ((binary-data
225           (string-append
226            (format #f "/~a ~s StartData " font-set-name (string-length body))
227            body))
228          (header
229           (format #f
230                   "%%BeginResource: font ~a
231 %!PS-Adobe-3.0 Resource-FontSet
232 %%DocumentNeededResources: ProcSet (FontSetInit)
233 %%Title: (FontSet/~a)
234 %%Version: ~s
235 %%EndComments
236 %%IncludeResource: ProcSet (FontSetInit)
237 %%BeginResource: FontSet (~a)
238 /FontSetInit /ProcSet findresource begin
239 %%BeginData: ~s Binary Bytes
240 "
241                   font-set-name font-set-name version font-set-name
242                   (string-length binary-data)))
243          (footer "\n%%EndData
244 %%EndResource
245 %%EndResource\n"))
246     (begin
247       (set! never-embed-font-list
248             (append never-embed-font-list (list font-set-name)))
249       (string-append header
250                      binary-data
251                      footer))))
252
253 (define check-conflict-and-embed-cff
254   (let ((font-list '()))
255     (lambda (name file-name font-index)
256       (if name
257           (let* ((name-symbol (string->symbol name))
258                  (args-filename-offset
259                   (cons file-name (ly:get-cff-offset file-name font-index)))
260                  (found-filename-offset (assq name-symbol font-list)))
261             (if found-filename-offset
262                 (begin
263                   (if (equal? args-filename-offset (cdr found-filename-offset))
264                       (ly:debug
265                        (_ "CFF font `~a' already embedded, skipping.")
266                        name)
267                       (ly:warning
268                        (_ "Different CFF fonts which have the same name `~a' has been detected. The font cannot be embedded.")
269                        name))
270                   "")
271                 (begin
272                   (ly:debug (_ "Embedding CFF font `~a'.") name)
273                   (set! font-list
274                         (acons name-symbol args-filename-offset font-list))
275                   (ps-embed-cff (ly:otf->cff file-name font-index) name 0))))
276           (begin
277             (ly:debug (_ "Initializing embedded CFF font list."))
278             (set! font-list '()))))))
279
280 (define (initialize-font-embedding)
281   (check-conflict-and-embed-cff #f #f #f))
282
283 (define (write-preamble paper load-fonts? port)
284   (define (internal-font? font-name-filename)
285     (let* ((font (car font-name-filename))
286            (file-name (caddr font-name-filename))
287            (font-file-name (ly:find-file (format #f "~a.otf" file-name))))
288       (and font
289            (cff-font? font)
290            font-file-name
291            (string-contains font-file-name
292                             (ly:get-option 'datadir)))))
293
294   (define (load-font-via-GS font-name-filename)
295     (define (is-collection-font? file-name)
296       (let* ((port (open-file file-name "rb"))
297              (retval
298               (if (eq? (read-char port) #\t)
299                   (if (eq? (read-char port) #\t)
300                       (if (eq? (read-char port) #\c)
301                           (if (eq? (read-char port) #\f)
302                               #t
303                               #f)
304                           #f)
305                       #f)
306                   #f)))
307         (close-port port)
308         retval))
309
310     (define (ps-load-file file-name)
311       (if (string? file-name)
312           (if (and (not (ly:get-option 'font-export-dir))
313                    (string-contains file-name (ly:get-option 'datadir)))
314               (begin
315                 (set! file-name (ly:string-substitute (ly:get-option 'datadir)
316                                                       "" file-name))
317                 (format #f
318                         "lilypond-datadir (~a) concatstrings (r) file .loadfont\n"
319                         file-name))
320               (format #f "(~a) (r) file .loadfont\n" file-name))
321           (format #f "% cannot find font file: ~a\n" file-name)))
322
323     (let* ((font (car font-name-filename))
324            (name (cadr font-name-filename))
325            (file-name (caddr font-name-filename))
326            (font-index (cadddr font-name-filename))
327            (bare-file-name (ly:find-file file-name)))
328       (cond
329        ((and (number? font-index)
330              (!= font-index 0))
331         (ly:warning (_ "Font ~a cannot be loaded via Ghostscript because its font-index (~a) is not zero.")
332                     name font-index)
333         (load-font font-name-filename))
334        ((and (string? bare-file-name)
335              (eq? (ly:get-font-format bare-file-name font-index) 'CFF)
336              (is-collection-font? bare-file-name))
337         (ly:warning (_ "Font ~a cannot be loaded via Ghostscript because it is an OpenType/CFF Collection (OTC) font.")
338                     name)
339         (load-font font-name-filename))
340        ((and (string? bare-file-name)
341              (eq? (ly:get-font-format bare-file-name font-index) 'TrueType)
342              (not (ly:has-glyph-names? bare-file-name font-index)))
343         (ly:warning (_ "Font ~a cannot be used via Ghostscript because it is a TrueType font that does not have glyph names.")
344                     name)
345         (load-font font-name-filename))
346        (else
347         (begin
348           (if (or (and font (cff-font? font))
349                   (and (string? bare-file-name)
350                        (not (eq? (ly:get-font-format
351                                   bare-file-name
352                                   font-index) 'TrueType))))
353               (set! never-embed-font-list
354                     (append never-embed-font-list (list name))))
355           (cons name
356                 (if (mac-font? bare-file-name)
357                     (handle-mac-font name bare-file-name)
358                     (cond
359                      ((and font (cff-font? font))
360                       (ps-load-file (ly:find-file
361                                      (format #f "~a.otf" file-name))))
362                      ((string? bare-file-name)
363                       (ps-load-file file-name))
364                      (else
365                       (ly:warning (_ "cannot embed ~S=~S") name file-name)
366                       "")))))))))
367
368   (define (dir-join a b)
369     (if (equal? a "")
370         b
371         (string-append a "/" b)))
372
373   (define (dir-listing dir-name)
374     (define (dir-helper dir lst)
375       (let ((e (readdir dir)))
376         (if (eof-object? e)
377             lst
378             (dir-helper dir (cons e lst)))))
379     (reverse (dir-helper (opendir dir-name) '())))
380
381   (define (handle-mac-font name file-name)
382     (let* ((dir-name (tmpnam))
383            (files '())
384            (status 0)
385            (embed #f)
386            (cwd (getcwd)))
387       (mkdir dir-name #o700)
388       (chdir dir-name)
389       (set! status (ly:system (list "fondu" "-force" file-name)))
390       (chdir cwd)
391       (set! files (dir-listing dir-name))
392       (for-each
393        (lambda (f)
394          (let* ((full-name (dir-join dir-name f)))
395            (if (and (not embed)
396                     (equal? 'regular (stat:type (stat full-name)))
397                     (equal? name (ly:ttf-ps-name full-name)))
398                (set! embed (font-file-as-ps-string name full-name 0)))
399            (if (or (equal? "." f)
400                    (equal? ".." f))
401                #t
402                (delete-file full-name))))
403        files)
404       (rmdir dir-name)
405       (if (not embed)
406           (begin
407             (set! embed "% failed\n")
408             (ly:warning (_ "cannot extract file matching ~a from ~a")
409                         name file-name)))
410       embed))
411
412   (define (font-file-as-ps-string name file-name font-index)
413     (let ((font-format (ly:get-font-format file-name font-index)))
414       (cond
415        ((eq? font-format (string->symbol "Type 1"))
416         ;; Type 1 (PFA and PFB) fonts
417         (begin (set! never-embed-font-list
418                      (append never-embed-font-list (list name)))
419                (ly:type1->pfa file-name)))
420        ((eq? font-format 'TrueType)
421         ;; TrueType fonts (TTF) and TrueType Collection (TTC)
422         (ly:ttf->pfa file-name font-index))
423        ((eq? font-format 'CFF)
424         ;; OpenType/CFF fonts (OTF) and OpenType/CFF Collection (OTC)
425         (check-conflict-and-embed-cff name file-name font-index))
426        (else
427         (ly:warning (_ "do not know how to embed ~S=~S") name file-name)
428         ""))))
429
430   (define (mac-font? bare-file-name)
431     (and (eq? PLATFORM 'darwin)
432          bare-file-name
433          (or (string-endswith bare-file-name ".dfont")
434              (= (stat:size (stat bare-file-name)) 0))))
435
436   (define (load-font font-psname-filename-fontindex)
437     (let* ((font (list-ref font-psname-filename-fontindex 0))
438            (name (list-ref font-psname-filename-fontindex 1))
439            (file-name (list-ref font-psname-filename-fontindex 2))
440            (font-index (list-ref font-psname-filename-fontindex 3))
441            (bare-file-name (ly:find-file file-name)))
442       (cons name
443             (cond ((mac-font? bare-file-name)
444                    (handle-mac-font name bare-file-name))
445                   ((and font (cff-font? font))
446                    (ps-embed-cff (ly:otf-font-table-data font "CFF ")
447                                  name
448                                  0))
449                   (bare-file-name (font-file-as-ps-string
450                                    name bare-file-name font-index))
451                   (else
452                    (ly:warning (_ "do not know how to embed font ~s ~s ~s")
453                                name file-name font))))))
454
455   (define (load-fonts paper)
456     (let* ((fonts (ly:paper-fonts paper))
457
458            ;; todo - doc format of list.
459            (all-font-names
460             (map
461              (lambda (font)
462                (cond ((string? (ly:font-file-name font))
463                       (list (list font
464                                   (ly:font-name font)
465                                   (ly:font-file-name font)
466                                   #f)))
467                      ((ly:pango-font? font)
468                       (map (lambda (psname-filename-fontindex)
469                              (list #f
470                                    (list-ref psname-filename-fontindex 0)
471                                    (list-ref psname-filename-fontindex 1)
472                                    (list-ref psname-filename-fontindex 2)))
473                            (ly:pango-font-physical-fonts font)))
474                      (else
475                       (ly:font-sub-fonts font))))
476              fonts))
477            (font-names (uniq-list
478                         (sort (concatenate all-font-names)
479                               (lambda (x y) (string<? (cadr x) (cadr y))))))
480
481            ;; slightly spaghetti-ish: deciding what to load where
482            ;; is smeared out.
483            (font-loader
484             (lambda (name)
485               (cond ((ly:get-option 'gs-load-fonts)
486                      (load-font-via-GS name))
487                     ((ly:get-option 'gs-load-lily-fonts)
488                      (if (or (string-contains (caddr name)
489                                               (ly:get-option 'datadir))
490                              (internal-font? name))
491                          (load-font-via-GS name)
492                          (load-font name)))
493                     (else
494                      (load-font name)))))
495            (pfas (map font-loader font-names)))
496       pfas))
497
498   (define (font-export name body)
499     (let* ((filename (format #f "~a/~a.font.ps"
500                              (ly:get-option 'font-export-dir)
501                              name))
502            (port-excl
503             (catch
504              'system-error
505              (lambda ()
506                ;; Exclusive file create:
507                ;; When the file already exists, it raises system-error.
508                (open filename (logior O_WRONLY O_CREAT O_EXCL)))
509              (lambda stuff
510                ;; Catch the system-error
511                (let ((errno (system-error-errno stuff)))
512                  (cond
513                   ;; If the file already exists, return #f.
514                   ((= errno EEXIST)
515                    (begin
516                      (ly:debug
517                        (_ "Font file `~a' already exists, skipping.")
518                        filename)
519                      #f))
520                   ;; If the cause is something else, re-throw the error.
521                   (#t
522                    (throw 'system-error (cdr stuff)))))))))
523       (if port-excl
524           ;; MinGW hack: need to have "b"inary for fonts
525           (let ((port (open-file filename "wb")))
526             (close port-excl)
527             (ly:debug (_ "Exporting font file `~a'.") filename)
528             (format port "%%BeginFont: ~a\n" name)
529             (display body port)
530             (display "%%EndFont\n" port)
531             (close-port port)))))
532
533   (display "%%BeginProlog\n" port)
534   (format
535    port
536    "/lilypond-datadir where {pop} {userdict /lilypond-datadir (~a) put } ifelse"
537    (ly:get-option 'datadir))
538   (set! never-embed-font-list (list))
539   (if (ly:get-option 'font-export-dir)
540       (let ((dirname (format #f "~a" (ly:get-option 'font-export-dir))))
541         (if (file-exists? dirname)
542             (ly:debug
543              (_ "Font export directory `~a' already exists.") dirname)
544             (begin
545               (ly:debug
546                (_ "Making font export directory `~a'.") dirname)
547               (mkdir dirname)))))
548   (if load-fonts?
549       (for-each (lambda (f)
550                   (format port "\n%%BeginFont: ~a\n" (car f))
551                   (display (cdr f) port)
552                   (display "%%EndFont\n" port)
553                   (if (ly:get-option 'font-export-dir)
554                       (font-export (car f) (cdr f))))
555                 (load-fonts paper)))
556   (if (ly:get-option 'gs-never-embed-fonts)
557       (begin
558         (display "\nsystemdict /DEVICE known\n" port)
559         (display " { systemdict /DEVICE get (pdfwrite) eq {\n" port)
560         (display ".setpdfwrite << /NeverEmbed [" port)
561         (display (string-concatenate
562                   (map (lambda (f) (string-append " /" f))
563                        never-embed-font-list)) port)
564         (display " ] >> setdistillerparams\n" port)
565         (display " } if } if\n" port)))
566   (if (ly:bigpdfs)
567       (display (procset "encodingdefs.ps") port))
568   (display (setup-variables paper) port)
569
570   ;; adobe note 5002: should initialize variables before loading routines.
571   (display (procset "music-drawing-routines.ps") port)
572   (display (procset "lilyponddefs.ps") port)
573   (display "%%EndProlog\n" port)
574   (display "%%BeginSetup\ninit-lilypond-parameters\n%%EndSetup\n\n" port))
575
576 (define (ps-quote str)
577   (fold
578    (lambda (replacement-list result)
579      (string-join
580       (string-split
581        result
582        (car replacement-list))
583       (cadr replacement-list)))
584    str
585    '((#\\ "\\\\") (#\( "\\(") (#\) "\\)"))))
586
587 ;;; Create DOCINFO pdfmark containing metadata
588 ;;; header fields with pdf prefix override those without the prefix
589 (define (handle-metadata header port)
590   (define (metadata-encode val)
591     ;; First, call ly:encode-string-for-pdf to encode the string (latin1 or
592     ;; utf-16be), then escape all parentheses and backslashes
593     ;; FIXME guile-2.0: use (string->utf16 str 'big) instead
594
595     (ps-quote (ly:encode-string-for-pdf val)))
596   (define (metadata-lookup-output overridevar fallbackvar field)
597     (let* ((overrideval (ly:modules-lookup (list header) overridevar))
598            (fallbackval (ly:modules-lookup (list header) fallbackvar))
599            (val (if overrideval overrideval fallbackval)))
600       (if val
601           (format port "/~a (~a)\n" field (metadata-encode (markup->string val (list header)))))))
602
603   (if (module? header)
604       (begin
605        (display "mark " port)
606        (metadata-lookup-output 'pdfauthor 'author "Author")
607        (format port "/Creator (LilyPond ~a)\n" (lilypond-version))
608        (metadata-lookup-output 'pdftitle 'title "Title")
609        (metadata-lookup-output 'pdfsubject 'subject "Subject")
610        (metadata-lookup-output 'pdfkeywords 'keywords "Keywords")
611        (metadata-lookup-output 'pdfmodDate 'modDate "ModDate")
612        (metadata-lookup-output 'pdfsubtitle 'subtitle "Subtitle")
613        (metadata-lookup-output 'pdfcomposer 'composer "Composer")
614        (metadata-lookup-output 'pdfarranger 'arranger "Arranger")
615        (metadata-lookup-output 'pdfpoet 'poet "Poet")
616        (metadata-lookup-output 'pdfcopyright 'copyright "Copyright")
617        (display "/DOCINFO pdfmark\n\n" port)))
618
619   (if (ly:get-option 'embed-source-code)
620       (let ((source-list (delete-duplicates
621                           (remove (lambda (str)
622                                     (or
623                                      (string-contains str
624                                        (ly:get-option 'datadir))
625                                      (string=? str
626                                        "<included string>")))
627                             (ly:source-files)))))
628          (display "\n/pdfmark where
629 {pop} {userdict /pdfmark /cleartomark load put} ifelse" port)
630          (for-each (lambda (fname idx)
631                      (format port "\n
632 mark /_objdef {ly~a_stream} /type /stream   /OBJ pdfmark
633 mark {ly~a_stream} << /Type /EmbeddedFile>> /PUT pdfmark
634 mark {ly~a_stream} (~a) /PUT pdfmark
635 mark /Name (LilyPond source file ~a)
636 /FS << /Type /Filespec /F (~a) /EF << /F {ly~a_stream} >> >> /EMBED pdfmark
637 mark {ly~a_stream} /CLOSE pdfmark
638 \n"
639                 idx idx idx
640                 (ps-quote (ly:gulp-file fname))
641                   idx fname idx idx))
642           source-list (iota (length source-list))))))
643
644 (define-public (output-framework basename book scopes fields)
645   (let* ((port-tmp (make-tmpfile))
646          (tmp-name (port-filename port-tmp))
647          (outputter (ly:make-paper-outputter
648                      port-tmp
649                      'ps))
650          (paper (ly:paper-book-paper book))
651          (header (ly:paper-book-header book))
652          (systems (ly:paper-book-systems book))
653          (page-stencils (map page-stencil (ly:paper-book-pages book)))
654          (landscape? (eq? (ly:output-def-lookup paper 'landscape) #t))
655          (page-number (1- (ly:output-def-lookup paper 'first-page-number)))
656          (page-count (length page-stencils))
657          (port (ly:outputter-port outputter)))
658     (initialize-font-embedding)
659     (if (ly:get-option 'clip-systems)
660         (clip-system-EPSes basename book))
661     (if (ly:get-option 'dump-signatures)
662         (write-system-signatures basename (ly:paper-book-systems book) 1))
663     (output-scopes scopes fields basename)
664     (display (file-header paper page-count #t) port)
665     ;; don't do BeginDefaults PageMedia: A4
666     ;; not necessary and wrong
667     (write-preamble paper #t port)
668     (handle-metadata header port)
669     (for-each
670      (lambda (page)
671        (set! page-number (1+ page-number))
672        (dump-page outputter page page-number page-count landscape?))
673      page-stencils)
674     (display "%%Trailer\n%%EOF\n" port)
675     (ly:outputter-close outputter)
676     (postprocess-output book framework-ps-module (ly:output-formats)
677                         basename tmp-name #f)))
678
679 (define-public (dump-stencil-as-EPS paper dump-me filename
680                                     load-fonts)
681   (let* ((xext (ly:stencil-extent dump-me X))
682          (yext (ly:stencil-extent dump-me Y))
683          (padding (ly:get-option 'eps-box-padding))
684          (left-overshoot (if (number? padding)
685                              (* -1 padding (ly:output-def-lookup paper 'mm))
686                              #f))
687          (bbox
688           (map
689            (lambda (x)
690              (if (or (nan? x) (inf? x)
691                      ;; FIXME: huh?
692                      (equal? (format #f "~S" x) "+#.#")
693                      (equal? (format #f "~S" x) "-#.#"))
694                  0.0 x))
695
696            ;; the left-overshoot is to make sure that
697            ;; bar numbers stick out of margin uniformly.
698            ;;
699            (list
700             (if (number? left-overshoot)
701                 (min left-overshoot (car xext))
702                 (car xext))
703             (car yext) (cdr xext) (cdr yext)))))
704     (dump-stencil-as-EPS-with-bbox paper dump-me filename load-fonts bbox)))
705
706 (define-public (dump-stencil-as-EPS-with-bbox paper dump-me filename
707                                               load-fonts
708                                               bbox)
709   "Create an EPS file from stencil @var{dump-me} to @var{filename}.
710 @var{bbox} has format @code{(left-x, lower-y, right-x, upper-y)}.  If
711 @var{load-fonts} set, include fonts inline."
712   (define (to-rounded-bp-box box)
713     "Convert box to 1/72 inch with rounding to enlarge the box."
714     (let* ((scale (ly:output-def-lookup paper 'output-scale))
715            (strip-non-number (lambda (x)
716                                (if (or (nan? x)
717                                        (inf? x))
718                                    0.0
719                                    x)))
720            (directed-round (lambda (x rounder)
721                              (inexact->exact
722                               (rounder (/ (* (strip-non-number x) scale)
723                                           (ly:bp 1)))))))
724       (list (directed-round (car box) floor)
725             (directed-round (cadr box) floor)
726             (directed-round (max (1+ (car box)) (caddr box)) ceiling)
727             (directed-round (max (1+ (cadr box)) (cadddr box)) ceiling))))
728
729   (let* ((outputter (ly:make-paper-outputter
730                      ;; FIXME: better wrap open/open-file,
731                      ;; content-mangling is always bad.
732                      ;; MINGW hack: need to have "b"inary for embedding CFFs
733                      (open-file (format #f "~a.eps" filename) "wb")
734                      'ps))
735          (port (ly:outputter-port outputter))
736          (rounded-bbox (to-rounded-bp-box bbox))
737          (port (ly:outputter-port outputter))
738          (header (eps-header paper rounded-bbox load-fonts)))
739     (initialize-font-embedding)
740     (display header port)
741     (write-preamble paper load-fonts port)
742     (display "/mark_page_link { pop pop pop pop pop } bind def\n" port)
743     (display "gsave set-ps-scale-to-lily-scale\n" port)
744     (display "/helpEmmentaler-Brace where {pop helpEmmentaler-Brace} if\n" port)
745     (display "/helpEmmentaler-11 where {pop helpEmmentaler-11} if\n" port)
746     (display "/helpEmmentaler-13 where {pop helpEmmentaler-13} if\n" port)
747     (display "/helpEmmentaler-14 where {pop helpEmmentaler-14} if\n" port)
748     (display "/helpEmmentaler-16 where {pop helpEmmentaler-16} if\n" port)
749     (display "/helpEmmentaler-18 where {pop helpEmmentaler-18} if\n" port)
750     (display "/helpEmmentaler-20 where {pop helpEmmentaler-20} if\n" port)
751     (display "/helpEmmentaler-23 where {pop helpEmmentaler-23} if\n" port)
752     (display "/helpEmmentaler-26 where {pop helpEmmentaler-26} if\n" port)
753     (ly:outputter-dump-stencil outputter dump-me)
754     (display "stroke grestore\n%%Trailer\n%%EOF\n" port)
755     (ly:outputter-close outputter)))
756
757 (define (clip-systems-to-region basename paper systems region do-pdf do-png)
758   (let* ((extents-system-pairs
759           (filtered-map (lambda (paper-system)
760                           (let* ((x-ext (system-clipped-x-extent
761                                          (paper-system-system-grob paper-system)
762                                          region)))
763                             (if x-ext
764                                 (cons x-ext paper-system)
765                                 #f)))
766                         systems))
767          (count 0))
768     (for-each
769      (lambda (ext-system-pair)
770        (let* ((xext (car ext-system-pair))
771               (paper-system (cdr ext-system-pair))
772               (yext (paper-system-extent paper-system Y))
773               (bbox (list (car xext) (car yext)
774                           (cdr xext) (cdr yext)))
775               (filename (if (< 0 count)
776                             (format #f "~a-~a" basename count)
777                             basename)))
778          (set! count (1+ count))
779          (dump-stencil-as-EPS-with-bbox paper
780                                         (paper-system-stencil paper-system)
781                                         filename
782                                         (ly:get-option 'include-eps-fonts)
783                                         bbox)
784          (if do-pdf
785              (postscript->pdf 0 0 filename (format #f "~a.eps" filename) #t))
786          (if do-png
787              (postscript->png (ly:get-option 'resolution) 0 0
788                               filename (format #f "~a.eps" filename) #t))))
789      extents-system-pairs)))
790
791 (define-public (clip-system-EPSes basename paper-book)
792   (define do-pdf
793     (member "pdf" (ly:output-formats)))
794   (define do-png
795     (member "png" (ly:output-formats)))
796
797   (define (clip-score-systems basename systems)
798     (let* ((layout (ly:grob-layout (paper-system-system-grob (car systems))))
799            (regions (ly:output-def-lookup layout 'clip-regions)))
800       (for-each
801        (lambda (region)
802          (clip-systems-to-region
803           (format #f "~a-from-~a-to-~a-clip"
804                   basename
805                   (rhythmic-location->file-string (car region))
806                   (rhythmic-location->file-string (cdr region)))
807           layout systems region
808           do-pdf do-png))
809        regions)))
810
811   ;; partition in system lists sharing their layout blocks
812   (let* ((systems (ly:paper-book-systems paper-book))
813          (count 0)
814          (score-system-list '()))
815     (fold
816      (lambda (system last-system)
817        (if (not (and last-system
818                      (equal? (paper-system-layout last-system)
819                              (paper-system-layout system))))
820            (set! score-system-list (cons '() score-system-list)))
821        (if (paper-system-layout system)
822            (set-car! score-system-list (cons system (car score-system-list))))
823        ;; pass value.
824        system)
825      #f
826      systems)
827     (for-each (lambda (system-list)
828                 ;; filter out headers and top-level markup
829                 (if (pair? system-list)
830                     (clip-score-systems
831                      (if (> count 0)
832                          (format #f "~a-~a" basename count)
833                          basename)
834                      system-list)))
835               score-system-list)))
836
837 (define-public (output-preview-framework basename book scopes fields)
838   (let* ((paper (ly:paper-book-paper book))
839          (systems (relevant-book-systems book))
840          (to-dump-systems (relevant-dump-systems systems)))
841     (dump-stencil-as-EPS paper
842                          (stack-stencils Y DOWN 0.0
843                                          (map paper-system-stencil
844                                               (reverse to-dump-systems)))
845                          (format #f "~a.preview" basename)
846                          #t)
847     (postprocess-output book framework-ps-module
848                         (cons "png" (ly:output-formats))
849                         (format #f "~a.preview" basename)
850                         (format #f "~a.preview.eps" basename)
851                         #t
852                         )))
853
854 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
855
856 (define (output-width-height defs)
857   (let* ((landscape (ly:output-def-lookup defs 'landscape))
858          (output-scale (ly:output-def-lookup defs 'output-scale))
859          (convert (lambda (x)
860                     (* x output-scale (/ (ly:bp 1)))))
861          (paper-width (convert (ly:output-def-lookup defs 'paper-width)))
862          (paper-height (convert (ly:output-def-lookup defs 'paper-height)))
863          (w (if landscape paper-height paper-width))
864          (h (if landscape paper-width paper-height)))
865     (cons w h)))
866
867 (define (output-resolution defs)
868   (let ((defs-resolution (ly:output-def-lookup defs 'pngresolution)))
869     (if (number? defs-resolution)
870         defs-resolution
871         (ly:get-option 'resolution))))
872
873 (define-public (convert-to-pdf book base-name tmp-name is-eps)
874   (let* ((defs (ly:paper-book-paper book))
875          (width-height (output-width-height defs))
876          (width (car width-height))
877          (height (cdr width-height)))
878     (postscript->pdf width height base-name tmp-name is-eps)))
879
880 (define-public (convert-to-png book base-name tmp-name is-eps)
881   (let* ((defs (ly:paper-book-paper book))
882          (resolution (output-resolution defs))
883          (width-height (output-width-height defs))
884          (width (car width-height))
885          (height (cdr width-height)))
886     (postscript->png resolution width height base-name tmp-name is-eps)))
887
888 (define-public (convert-to-ps book base-name tmp-name is-eps)
889   (postscript->ps base-name tmp-name is-eps))
890
891 (define-public (output-classic-framework basename book scopes fields)
892   (ly:error (_ "\nThe PostScript backend does not support the
893 system-by-system output.  For that, use the EPS backend instead,
894
895   lilypond -dbackend=eps FILE
896
897 If you have cut & pasted a lilypond fragment from a webpage, be sure
898 to only remove anything before
899
900   %% ****************************************************************
901   %% Start cut-&-pastable-section
902   %% ****************************************************************
903 ")))