]> git.donarmstrong.com Git - lilypond.git/blob - scm/framework-ps.scm
Merge branch 'master' into translation
[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         (ly:debug
542          (_ "Making font export directory `~a'.") dirname)
543         (catch
544          'system-error
545          (lambda ()
546            ;; mkdir:
547            ;; When the directory already exists, it raises system-error.
548            (mkdir dirname))
549          (lambda stuff
550            ;; Catch the system-error
551            (if (= EEXIST (system-error-errno stuff))
552                ;; If the directory already exists, avoid error.
553                (ly:debug
554                 (_ "Font export directory `~a' already exists.") dirname)
555                ;; If the cause is something else, re-throw the error.
556                (throw 'system-error (cdr stuff)))))))
557   (if load-fonts?
558       (for-each (lambda (f)
559                   (format port "\n%%BeginFont: ~a\n" (car f))
560                   (display (cdr f) port)
561                   (display "%%EndFont\n" port)
562                   (if (ly:get-option 'font-export-dir)
563                       (font-export (car f) (cdr f))))
564                 (load-fonts paper)))
565   (if (ly:get-option 'gs-never-embed-fonts)
566       (begin
567         (display "\nsystemdict /DEVICE known\n" port)
568         (display " { systemdict /DEVICE get (pdfwrite) eq {\n" port)
569         (display ".setpdfwrite << /NeverEmbed [" port)
570         (display (string-concatenate
571                   (map (lambda (f) (string-append " /" f))
572                        never-embed-font-list)) port)
573         (display " ] >> setdistillerparams\n" port)
574         (display " } if } if\n" port)))
575   (if (ly:bigpdfs)
576       (display (procset "encodingdefs.ps") port))
577   (display (setup-variables paper) port)
578
579   ;; adobe note 5002: should initialize variables before loading routines.
580   (display (procset "music-drawing-routines.ps") port)
581   (display (procset "lilyponddefs.ps") port)
582   (display "%%EndProlog\n" port)
583   (display "%%BeginSetup\ninit-lilypond-parameters\n%%EndSetup\n\n" port))
584
585 (define (ps-quote str)
586   (fold
587    (lambda (replacement-list result)
588      (string-join
589       (string-split
590        result
591        (car replacement-list))
592       (cadr replacement-list)))
593    str
594    '((#\\ "\\\\") (#\( "\\(") (#\) "\\)"))))
595
596 ;;; Create DOCINFO pdfmark containing metadata
597 ;;; header fields with pdf prefix override those without the prefix
598 (define (handle-metadata header port)
599   (define (metadata-encode val)
600     ;; First, call ly:encode-string-for-pdf to encode the string (latin1 or
601     ;; utf-16be), then escape all parentheses and backslashes
602     ;; FIXME guile-2.0: use (string->utf16 str 'big) instead
603
604     (ps-quote (ly:encode-string-for-pdf val)))
605   (define (metadata-lookup-output overridevar fallbackvar field)
606     (let* ((overrideval (ly:modules-lookup (list header) overridevar))
607            (fallbackval (ly:modules-lookup (list header) fallbackvar))
608            (val (if overrideval overrideval fallbackval)))
609       (if val
610           (format port "/~a (~a)\n" field (metadata-encode (markup->string val (list header)))))))
611
612   (if (module? header)
613       (begin
614        (display "mark " port)
615        (metadata-lookup-output 'pdfauthor 'author "Author")
616        (format port "/Creator (LilyPond ~a)\n" (lilypond-version))
617        (metadata-lookup-output 'pdftitle 'title "Title")
618        (metadata-lookup-output 'pdfsubject 'subject "Subject")
619        (metadata-lookup-output 'pdfkeywords 'keywords "Keywords")
620        (metadata-lookup-output 'pdfmodDate 'modDate "ModDate")
621        (metadata-lookup-output 'pdfsubtitle 'subtitle "Subtitle")
622        (metadata-lookup-output 'pdfcomposer 'composer "Composer")
623        (metadata-lookup-output 'pdfarranger 'arranger "Arranger")
624        (metadata-lookup-output 'pdfpoet 'poet "Poet")
625        (metadata-lookup-output 'pdfcopyright 'copyright "Copyright")
626        (display "/DOCINFO pdfmark\n\n" port)))
627
628   (if (ly:get-option 'embed-source-code)
629       (let ((source-list (delete-duplicates
630                           (remove (lambda (str)
631                                     (or
632                                      (string-contains str
633                                        (ly:get-option 'datadir))
634                                      (string=? str
635                                        "<included string>")))
636                             (ly:source-files)))))
637          (display "\n/pdfmark where
638 {pop} {userdict /pdfmark /cleartomark load put} ifelse" port)
639          (for-each (lambda (fname idx)
640                      (format port "\n
641 mark /_objdef {ly~a_stream} /type /stream   /OBJ pdfmark
642 mark {ly~a_stream} << /Type /EmbeddedFile>> /PUT pdfmark
643 mark {ly~a_stream} (~a) /PUT pdfmark
644 mark /Name (LilyPond source file ~a)
645 /FS << /Type /Filespec /F (~a) /EF << /F {ly~a_stream} >> >> /EMBED pdfmark
646 mark {ly~a_stream} /CLOSE pdfmark
647 \n"
648                 idx idx idx
649                 (ps-quote (ly:gulp-file fname))
650                   idx fname idx idx))
651           source-list (iota (length source-list))))))
652
653 (define-public (output-framework basename book scopes fields)
654   (let* ((port-tmp (make-tmpfile))
655          (tmp-name (port-filename port-tmp))
656          (outputter (ly:make-paper-outputter
657                      port-tmp
658                      'ps))
659          (paper (ly:paper-book-paper book))
660          (header (ly:paper-book-header book))
661          (systems (ly:paper-book-systems book))
662          (page-stencils (map page-stencil (ly:paper-book-pages book)))
663          (landscape? (eq? (ly:output-def-lookup paper 'landscape) #t))
664          (page-number (1- (ly:output-def-lookup paper 'first-page-number)))
665          (page-count (length page-stencils))
666          (port (ly:outputter-port outputter)))
667     (initialize-font-embedding)
668     (if (ly:get-option 'clip-systems)
669         (clip-system-EPSes basename book))
670     (if (ly:get-option 'dump-signatures)
671         (write-system-signatures basename (ly:paper-book-systems book) 1))
672     (output-scopes scopes fields basename)
673     (display (file-header paper page-count #t) port)
674     ;; don't do BeginDefaults PageMedia: A4
675     ;; not necessary and wrong
676     (write-preamble paper #t port)
677     (handle-metadata header port)
678     (for-each
679      (lambda (page)
680        (set! page-number (1+ page-number))
681        (dump-page outputter page page-number page-count landscape?))
682      page-stencils)
683     (display "%%Trailer\n%%EOF\n" port)
684     (ly:outputter-close outputter)
685     (postprocess-output book framework-ps-module (ly:output-formats)
686                         basename tmp-name #f)))
687
688 (define-public (dump-stencil-as-EPS paper dump-me filename
689                                     load-fonts)
690   (let* ((xext (ly:stencil-extent dump-me X))
691          (yext (ly:stencil-extent dump-me Y))
692          (padding (ly:get-option 'eps-box-padding))
693          (left-overshoot (if (number? padding)
694                              (* -1 padding (ly:output-def-lookup paper 'mm))
695                              #f))
696          (bbox
697           (map
698            (lambda (x)
699              (if (or (nan? x) (inf? x)
700                      ;; FIXME: huh?
701                      (equal? (format #f "~S" x) "+#.#")
702                      (equal? (format #f "~S" x) "-#.#"))
703                  0.0 x))
704
705            ;; the left-overshoot is to make sure that
706            ;; bar numbers stick out of margin uniformly.
707            ;;
708            (list
709             (if (number? left-overshoot)
710                 (min left-overshoot (car xext))
711                 (car xext))
712             (car yext) (cdr xext) (cdr yext)))))
713     (dump-stencil-as-EPS-with-bbox paper dump-me filename load-fonts bbox)))
714
715 (define-public (dump-stencil-as-EPS-with-bbox paper dump-me filename
716                                               load-fonts
717                                               bbox)
718   "Create an EPS file from stencil @var{dump-me} to @var{filename}.
719 @var{bbox} has format @code{(left-x, lower-y, right-x, upper-y)}.  If
720 @var{load-fonts} set, include fonts inline."
721   (define (to-rounded-bp-box box)
722     "Convert box to 1/72 inch with rounding to enlarge the box."
723     (let* ((scale (ly:output-def-lookup paper 'output-scale))
724            (strip-non-number (lambda (x)
725                                (if (or (nan? x)
726                                        (inf? x))
727                                    0.0
728                                    x)))
729            (directed-round (lambda (x rounder)
730                              (inexact->exact
731                               (rounder (/ (* (strip-non-number x) scale)
732                                           (ly:bp 1)))))))
733       (list (directed-round (car box) floor)
734             (directed-round (cadr box) floor)
735             (directed-round (max (1+ (car box)) (caddr box)) ceiling)
736             (directed-round (max (1+ (cadr box)) (cadddr box)) ceiling))))
737
738   (let* ((outputter (ly:make-paper-outputter
739                      ;; FIXME: better wrap open/open-file,
740                      ;; content-mangling is always bad.
741                      ;; MINGW hack: need to have "b"inary for embedding CFFs
742                      (open-file (format #f "~a.eps" filename) "wb")
743                      'ps))
744          (port (ly:outputter-port outputter))
745          (rounded-bbox (to-rounded-bp-box bbox))
746          (port (ly:outputter-port outputter))
747          (header (eps-header paper rounded-bbox load-fonts)))
748     (initialize-font-embedding)
749     (display header port)
750     (write-preamble paper load-fonts port)
751     (display "/mark_page_link { pop pop pop pop pop } bind def\n" port)
752     (display "gsave set-ps-scale-to-lily-scale\n" port)
753     (display "/helpEmmentaler-Brace where {pop helpEmmentaler-Brace} if\n" port)
754     (display "/helpEmmentaler-11 where {pop helpEmmentaler-11} if\n" port)
755     (display "/helpEmmentaler-13 where {pop helpEmmentaler-13} if\n" port)
756     (display "/helpEmmentaler-14 where {pop helpEmmentaler-14} if\n" port)
757     (display "/helpEmmentaler-16 where {pop helpEmmentaler-16} if\n" port)
758     (display "/helpEmmentaler-18 where {pop helpEmmentaler-18} if\n" port)
759     (display "/helpEmmentaler-20 where {pop helpEmmentaler-20} if\n" port)
760     (display "/helpEmmentaler-23 where {pop helpEmmentaler-23} if\n" port)
761     (display "/helpEmmentaler-26 where {pop helpEmmentaler-26} if\n" port)
762     (ly:outputter-dump-stencil outputter dump-me)
763     (display "stroke grestore\n%%Trailer\n%%EOF\n" port)
764     (ly:outputter-close outputter)))
765
766 (define (clip-systems-to-region basename paper systems region do-pdf do-png)
767   (let* ((extents-system-pairs
768           (filtered-map (lambda (paper-system)
769                           (let* ((x-ext (system-clipped-x-extent
770                                          (paper-system-system-grob paper-system)
771                                          region)))
772                             (if x-ext
773                                 (cons x-ext paper-system)
774                                 #f)))
775                         systems))
776          (count 0))
777     (for-each
778      (lambda (ext-system-pair)
779        (let* ((xext (car ext-system-pair))
780               (paper-system (cdr ext-system-pair))
781               (yext (paper-system-extent paper-system Y))
782               (bbox (list (car xext) (car yext)
783                           (cdr xext) (cdr yext)))
784               (filename (if (< 0 count)
785                             (format #f "~a-~a" basename count)
786                             basename)))
787          (set! count (1+ count))
788          (dump-stencil-as-EPS-with-bbox paper
789                                         (paper-system-stencil paper-system)
790                                         filename
791                                         (ly:get-option 'include-eps-fonts)
792                                         bbox)
793          (if do-pdf
794              (postscript->pdf 0 0 filename (format #f "~a.eps" filename) #t))
795          (if do-png
796              (postscript->png (ly:get-option 'resolution) 0 0
797                               filename (format #f "~a.eps" filename) #t))))
798      extents-system-pairs)))
799
800 (define-public (clip-system-EPSes basename paper-book)
801   (define do-pdf
802     (member "pdf" (ly:output-formats)))
803   (define do-png
804     (member "png" (ly:output-formats)))
805
806   (define (clip-score-systems basename systems)
807     (let* ((layout (ly:grob-layout (paper-system-system-grob (car systems))))
808            (regions (ly:output-def-lookup layout 'clip-regions)))
809       (for-each
810        (lambda (region)
811          (clip-systems-to-region
812           (format #f "~a-from-~a-to-~a-clip"
813                   basename
814                   (rhythmic-location->file-string (car region))
815                   (rhythmic-location->file-string (cdr region)))
816           layout systems region
817           do-pdf do-png))
818        regions)))
819
820   ;; partition in system lists sharing their layout blocks
821   (let* ((systems (ly:paper-book-systems paper-book))
822          (count 0)
823          (score-system-list '()))
824     (fold
825      (lambda (system last-system)
826        (if (not (and last-system
827                      (equal? (paper-system-layout last-system)
828                              (paper-system-layout system))))
829            (set! score-system-list (cons '() score-system-list)))
830        (if (paper-system-layout system)
831            (set-car! score-system-list (cons system (car score-system-list))))
832        ;; pass value.
833        system)
834      #f
835      systems)
836     (for-each (lambda (system-list)
837                 ;; filter out headers and top-level markup
838                 (if (pair? system-list)
839                     (clip-score-systems
840                      (if (> count 0)
841                          (format #f "~a-~a" basename count)
842                          basename)
843                      system-list)))
844               score-system-list)))
845
846 (define-public (output-preview-framework basename book scopes fields)
847   (let* ((paper (ly:paper-book-paper book))
848          (systems (relevant-book-systems book))
849          (to-dump-systems (relevant-dump-systems systems)))
850     (dump-stencil-as-EPS paper
851                          (stack-stencils Y DOWN 0.0
852                                          (map paper-system-stencil
853                                               (reverse to-dump-systems)))
854                          (format #f "~a.preview" basename)
855                          #t)
856     (postprocess-output book framework-ps-module
857                         (cons "png" (ly:output-formats))
858                         (format #f "~a.preview" basename)
859                         (format #f "~a.preview.eps" basename)
860                         #t
861                         )))
862
863 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
864
865 (define (output-width-height defs)
866   (let* ((landscape (ly:output-def-lookup defs 'landscape))
867          (output-scale (ly:output-def-lookup defs 'output-scale))
868          (convert (lambda (x)
869                     (* x output-scale (/ (ly:bp 1)))))
870          (paper-width (convert (ly:output-def-lookup defs 'paper-width)))
871          (paper-height (convert (ly:output-def-lookup defs 'paper-height)))
872          (w (if landscape paper-height paper-width))
873          (h (if landscape paper-width paper-height)))
874     (cons w h)))
875
876 (define (output-resolution defs)
877   (let ((defs-resolution (ly:output-def-lookup defs 'pngresolution)))
878     (if (number? defs-resolution)
879         defs-resolution
880         (ly:get-option 'resolution))))
881
882 (define-public (convert-to-pdf book base-name tmp-name is-eps)
883   (let* ((defs (ly:paper-book-paper book))
884          (width-height (output-width-height defs))
885          (width (car width-height))
886          (height (cdr width-height)))
887     (postscript->pdf width height base-name tmp-name is-eps)))
888
889 (define-public (convert-to-png book base-name tmp-name is-eps)
890   (let* ((defs (ly:paper-book-paper book))
891          (resolution (output-resolution defs))
892          (width-height (output-width-height defs))
893          (width (car width-height))
894          (height (cdr width-height)))
895     (postscript->png resolution width height base-name tmp-name is-eps)))
896
897 (define-public (convert-to-ps book base-name tmp-name is-eps)
898   (postscript->ps base-name tmp-name is-eps))
899
900 (define-public (output-classic-framework basename book scopes fields)
901   (ly:error (_ "\nThe PostScript backend does not support the
902 system-by-system output.  For that, use the EPS backend instead,
903
904   lilypond -dbackend=eps FILE
905
906 If you have cut & pasted a lilypond fragment from a webpage, be sure
907 to only remove anything before
908
909   %% ****************************************************************
910   %% Start cut-&-pastable-section
911   %% ****************************************************************
912 ")))