1 ;;;; This file is part of LilyPond, the GNU music typesetter.
3 ;;;; Copyright (C) 2004--2012 Han-Wen Nienhuys <hanwen@xs4all.nl>
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.
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.
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/>.
18 (define-module (scm framework-ps))
20 ;;; this is still too big a mess.
22 (use-modules (ice-9 string-fun)
31 (define format ergonomic-simple-format)
33 (define framework-ps-module (current-module))
35 ;;(define pdebug stderr)
36 (define (pdebug . rest) #f)
38 (define-public (ps-font-command font)
39 (let* ((name (ly:font-file-name font))
40 (magnify (ly:font-magnification font)))
49 "m" (string-encode-integer (inexact->exact (round (* 1000 magnify)))))))
51 (define (ps-define-pango-pf pango-pf font-name scaling)
54 (define (ps-define-font font font-name scaling)
56 "/" (ps-font-command font)
58 " " (ly:number->string scaling) " output-scale div selectfont }"
61 ;; FIXME: duplicated in other output backends
62 ;; FIXME: silly interface name
63 (define (output-variables layout)
64 ;; FIXME: duplicates output-layout's scope-entry->string, mostly
65 (define (value->string val)
67 ((string? val) (string-append "(" val ")"))
68 ((symbol? val) (symbol->string val))
69 ((number? val) (number->string val))
72 (define (output-entry ps-key ly-key)
75 (value->string (ly:output-def-lookup layout ly-key)) " def\n"))
79 (number->string (/ (ly:bp 1))) " def %% millimeter\n"
80 (output-entry "staff-line-thickness" 'line-thickness)
81 (output-entry "line-width" 'line-width)
82 (output-entry "paper-size" 'papersizename)
83 (output-entry "staff-height" 'staff-height) ;junkme.
85 (number->string (ly:output-def-lookup layout 'output-scale)) " def\n"
86 (output-entry "page-height" 'paper-height)
87 (output-entry "page-width" 'paper-width)))
89 (define (dump-page outputter page page-number page-count landscape?)
90 (ly:outputter-dump-string
93 (format #f "%%Page: ~a ~a\n" page-number page-number)
96 "page-width output-scale lily-output-units mul mul 0 translate 90 rotate\n"
100 "true setstrokeadjust\n"
101 "gsave 0 paper-height translate set-ps-scale-to-lily-scale\n"))
102 (ly:outputter-dump-stencil outputter page)
103 (ly:outputter-dump-string outputter "stroke grestore\nshowpage\n"))
105 (define (supplies-or-needs paper load-fonts?)
106 (define (extract-names font)
107 (if (ly:pango-font? font)
108 (map car (ly:pango-font-physical-fonts font))
109 (list (ly:font-name font))))
111 (let* ((fonts (ly:paper-fonts paper))
112 (names (append-map extract-names fonts)))
117 "%%DocumentSuppliedResources: font ~a\n"
118 "%%DocumentNeededResources: font ~a\n")
120 (uniq-list (sort names string<?))))))
122 (define (eps-header paper bbox load-fonts?)
123 (string-append "%!PS-Adobe-2.0 EPSF-2.0\n"
124 "%%Creator: LilyPond " (lilypond-version) "\n"
126 (string-join (map ly:number->string bbox) " ") "\n"
128 (if (eq? (ly:output-def-lookup paper 'landscape) #t)
131 (supplies-or-needs paper load-fonts?)
134 (define (ps-document-media paper)
136 (ly:output-def-lookup paper 'output-scale)
137 (ly:output-def-lookup paper 'paper-width)) (ly:bp 1)))
139 (ly:output-def-lookup paper 'paper-height)
140 (ly:output-def-lookup paper 'output-scale))
142 (landscape? (eq? (ly:output-def-lookup paper 'landscape) #t)))
143 (ly:format "%%DocumentMedia: ~a ~2f ~2f ~a ~a ~a\n"
144 (ly:output-def-lookup paper 'papersizename)
152 (define (file-header paper page-count load-fonts?)
153 (string-append "%!PS-Adobe-3.0\n"
154 "%%Creator: LilyPond " (lilypond-version) "\n"
155 "%%Pages: " (number->string page-count) "\n"
156 "%%PageOrder: Ascend\n"
158 (if (eq? (ly:output-def-lookup paper 'landscape) #t)
161 (ps-document-media paper)
162 (supplies-or-needs paper load-fonts?)
165 (define (procset file-name)
167 "%%BeginResource: procset (~a) 1 0
171 file-name (cached-file-contents file-name)))
173 (define (embed-document file-name)
174 (format #f "%%BeginDocument: ~a
178 file-name (cached-file-contents file-name)))
180 (define (setup-variables paper)
183 (define-fonts paper ps-define-font ps-define-pango-pf)
184 (output-variables paper)))
186 (define (cff-font? font)
187 (let* ((cff-string (ly:otf-font-table-data font "CFF ")))
188 (> (string-length cff-string) 0)))
190 (define-public (ps-embed-cff body font-set-name version)
193 (format #f "/~a ~s StartData " font-set-name (string-length body))
197 "%%BeginResource: font ~a
198 %!PS-Adobe-3.0 Resource-FontSet
199 %%DocumentNeededResources: ProcSet (FontSetInit)
200 %%Title: (FontSet/~a)
203 %%IncludeResource: ProcSet (FontSetInit)
204 %%BeginResource: FontSet (~a)
205 /FontSetInit /ProcSet findresource begin
206 %%BeginData: ~s Binary Bytes
208 font-set-name font-set-name version font-set-name
209 (string-length binary-data)))
213 (string-append header
217 (define (write-preamble paper load-fonts? port)
218 (define (internal-font? file-name)
219 (or (string-startswith file-name "Emmentaler")
220 (string-startswith file-name "emmentaler")
223 (define (load-font-via-GS font-name-filename)
224 (define (ps-load-file file-name)
225 (if (string? file-name)
226 (if (string-contains file-name (ly:get-option 'datadir))
228 (set! file-name (ly:string-substitute (ly:get-option 'datadir)
231 "lilypond-datadir (~a) concatstrings (r) file .loadfont\n"
233 (format #f "(~a) (r) file .loadfont\n" file-name))
234 (format #f "% cannot find font file: ~a\n" file-name)))
236 (let* ((font (car font-name-filename))
237 (name (cadr font-name-filename))
238 (file-name (caddr font-name-filename))
239 (bare-file-name (ly:find-file file-name)))
241 (if (mac-font? bare-file-name)
242 (handle-mac-font name bare-file-name)
244 ((internal-font? file-name)
245 (ps-load-file (ly:find-file
246 (format #f "~a.otf" file-name))))
247 ((string? bare-file-name)
248 (ps-load-file file-name))
250 (ly:warning (_ "cannot embed ~S=~S") name file-name)
253 (define (dir-join a b)
256 (string-append a "/" b)))
258 (define (dir-listing dir-name)
259 (define (dir-helper dir lst)
260 (let ((e (readdir dir)))
263 (dir-helper dir (cons e lst)))))
264 (reverse (dir-helper (opendir dir-name) '())))
266 (define (handle-mac-font name file-name)
267 (let* ((dir-name (tmpnam))
272 (mkdir dir-name #o700)
274 (set! status (ly:system (list "fondu" "-force" file-name)))
276 (set! files (dir-listing dir-name))
279 (let* ((full-name (dir-join dir-name f)))
281 (equal? 'regular (stat:type (stat full-name)))
282 (equal? name (ly:ttf-ps-name full-name)))
283 (set! embed (font-file-as-ps-string name full-name 0)))
284 (if (or (equal? "." f)
287 (delete-file full-name))))
292 (set! embed "% failed\n")
293 (ly:warning (_ "cannot extract file matching ~a from ~a")
297 (define (font-file-as-ps-string name file-name font-index)
298 (let* ((downcase-file-name (string-downcase file-name)))
300 ((and file-name (string-endswith downcase-file-name ".pfa"))
301 (embed-document file-name))
302 ((and file-name (string-endswith downcase-file-name ".pfb"))
303 (ly:pfb->pfa file-name))
304 ((and file-name (string-endswith downcase-file-name ".ttf"))
305 (ly:ttf->pfa file-name))
306 ((and file-name (string-endswith downcase-file-name ".ttc"))
307 (ly:ttf->pfa file-name font-index))
308 ((and file-name (string-endswith downcase-file-name ".otf"))
309 (ps-embed-cff (ly:otf->cff file-name) name 0))
311 (ly:warning (_ "do not know how to embed ~S=~S") name file-name)
314 (define (mac-font? bare-file-name)
315 (and (eq? PLATFORM 'darwin)
317 (or (string-endswith bare-file-name ".dfont")
318 (= (stat:size (stat bare-file-name)) 0))))
320 (define (load-font font-psname-filename-fontindex)
321 (let* ((font (list-ref font-psname-filename-fontindex 0))
322 (name (list-ref font-psname-filename-fontindex 1))
323 (file-name (list-ref font-psname-filename-fontindex 2))
324 (font-index (list-ref font-psname-filename-fontindex 3))
325 (bare-file-name (ly:find-file file-name)))
327 (cond ((mac-font? bare-file-name)
328 (handle-mac-font name bare-file-name))
329 ((and font (cff-font? font))
330 (ps-embed-cff (ly:otf-font-table-data font "CFF ")
333 (bare-file-name (font-file-as-ps-string
334 name bare-file-name font-index))
336 (ly:warning (_ "do not know how to embed font ~s ~s ~s")
337 name file-name font))))))
339 (define (load-fonts paper)
340 (let* ((fonts (ly:paper-fonts paper))
342 ;; todo - doc format of list.
346 (cond ((string? (ly:font-file-name font))
349 (ly:font-file-name font)
351 ((ly:pango-font? font)
352 (map (lambda (psname-filename-fontindex)
354 (list-ref psname-filename-fontindex 0)
355 (list-ref psname-filename-fontindex 1)
356 (list-ref psname-filename-fontindex 2)))
357 (ly:pango-font-physical-fonts font)))
359 (ly:font-sub-fonts font))))
361 (font-names (uniq-list
362 (sort (concatenate all-font-names)
363 (lambda (x y) (string<? (cadr x) (cadr y))))))
365 ;; slightly spaghetti-ish: deciding what to load where
369 (cond ((ly:get-option 'gs-load-fonts)
370 (load-font-via-GS name))
371 ((ly:get-option 'gs-load-lily-fonts)
372 (if (or (string-contains (caddr name)
373 (ly:get-option 'datadir))
374 (internal-font? (caddr name)))
375 (load-font-via-GS name)
379 (pfas (map font-loader font-names)))
383 (display "%%BeginProlog\n" port)
386 "/lilypond-datadir where {pop} {userdict /lilypond-datadir (~a) put } ifelse"
387 (ly:get-option 'datadir))
389 (for-each (lambda (f)
390 (format port "\n%%BeginFont: ~a\n" (car f))
391 (display (cdr f) port)
392 (display "%%EndFont\n" port))
394 (display (setup-variables paper) port)
396 ;; adobe note 5002: should initialize variables before loading routines.
397 (display (procset "music-drawing-routines.ps") port)
398 (display (procset "lilyponddefs.ps") port)
399 (display "%%EndProlog\n" port)
400 (display "%%BeginSetup\ninit-lilypond-parameters\n%%EndSetup\n\n" port))
402 (define (ps-quote str)
404 (lambda (replacement-list result)
408 (car replacement-list))
409 (cadr replacement-list)))
411 '((#\\ "\\\\") (#\( "\\(") (#\) "\\)"))))
413 ;;; Create DOCINFO pdfmark containing metadata
414 ;;; header fields with pdf prefix override those without the prefix
415 (define (handle-metadata header port)
416 (define (metadata-encode val)
417 ;; First, call ly:encode-string-for-pdf to encode the string (latin1 or
418 ;; utf-16be), then escape all parentheses and backslashes
419 ;; FIXME guile-2.0: use (string->utf16 str 'big) instead
421 (ps-quote (ly:encode-string-for-pdf val)))
422 (define (metadata-lookup-output overridevar fallbackvar field)
423 (let* ((overrideval (ly:modules-lookup (list header) overridevar))
424 (fallbackval (ly:modules-lookup (list header) fallbackvar))
425 (val (if overrideval overrideval fallbackval)))
427 (format port "/~a (~a)\n" field (metadata-encode (markup->string val (list header)))))))
429 (metadata-lookup-output 'pdfcomposer 'composer "Author")
430 (format port "/Creator (LilyPond ~a)\n" (lilypond-version))
431 (metadata-lookup-output 'pdftitle 'title "Title")
432 (metadata-lookup-output 'pdfsubject 'subject "Subject")
433 (metadata-lookup-output 'pdfkeywords 'keywords "Keywords")
434 (metadata-lookup-output 'pdfmodDate 'modDate "ModDate")
435 (metadata-lookup-output 'pdfsubtitle 'subtitle "Subtitle")
436 (metadata-lookup-output 'pdfcomposer 'composer "Composer")
437 (metadata-lookup-output 'pdfarranger 'arranger "Arranger")
438 (metadata-lookup-output 'pdfpoet 'poet "Poet")
439 (metadata-lookup-output 'pdfcopyright 'copyright "Copyright")
440 (display "/DOCINFO pdfmark\n\n" port))
443 (define-public (output-framework basename book scopes fields)
444 (let* ((filename (format #f "~a.ps" basename))
445 (outputter (ly:make-paper-outputter
446 ;; FIXME: better wrap open/open-file,
447 ;; content-mangling is always bad.
448 ;; MINGW hack: need to have "b"inary for embedding CFFs
449 (open-file filename "wb")
451 (paper (ly:paper-book-paper book))
452 (header (ly:paper-book-header book))
453 (systems (ly:paper-book-systems book))
454 (page-stencils (map page-stencil (ly:paper-book-pages book)))
455 (landscape? (eq? (ly:output-def-lookup paper 'landscape) #t))
456 (page-number (1- (ly:output-def-lookup paper 'first-page-number)))
457 (page-count (length page-stencils))
458 (port (ly:outputter-port outputter)))
459 (if (ly:get-option 'clip-systems)
460 (clip-system-EPSes basename book))
461 (if (ly:get-option 'dump-signatures)
462 (write-system-signatures basename (ly:paper-book-systems book) 1))
463 (output-scopes scopes fields basename)
464 (display (file-header paper page-count #t) port)
465 ;; don't do BeginDefaults PageMedia: A4
466 ;; not necessary and wrong
467 (write-preamble paper #t port)
469 (handle-metadata header port))
472 (set! page-number (1+ page-number))
473 (dump-page outputter page page-number page-count landscape?))
475 (display "%%Trailer\n%%EOF\n" port)
476 (ly:outputter-close outputter)
477 (postprocess-output book framework-ps-module filename
478 (ly:output-formats))))
480 (define-public (dump-stencil-as-EPS paper dump-me filename
482 (let* ((xext (ly:stencil-extent dump-me X))
483 (yext (ly:stencil-extent dump-me Y))
484 (padding (ly:get-option 'eps-box-padding))
485 (left-overshoot (if (number? padding)
486 (* -1 padding (ly:output-def-lookup paper 'mm))
491 (if (or (nan? x) (inf? x)
493 (equal? (format #f "~S" x) "+#.#")
494 (equal? (format #f "~S" x) "-#.#"))
497 ;; the left-overshoot is to make sure that
498 ;; bar numbers stick out of margin uniformly.
501 (if (number? left-overshoot)
502 (min left-overshoot (car xext))
504 (car yext) (cdr xext) (cdr yext)))))
505 (dump-stencil-as-EPS-with-bbox paper dump-me filename load-fonts bbox)))
507 (define-public (dump-stencil-as-EPS-with-bbox paper dump-me filename
510 "Create an EPS file from stencil @var{dump-me} to @var{filename}.
511 @var{bbox} has format @code{(left-x, lower-y, right-x, upper-y)}. If
512 @var{load-fonts} set, include fonts inline."
513 (define (to-rounded-bp-box box)
514 "Convert box to 1/72 inch with rounding to enlarge the box."
515 (let* ((scale (ly:output-def-lookup paper 'output-scale))
516 (strip-non-number (lambda (x)
521 (directed-round (lambda (x rounder)
523 (rounder (/ (* (strip-non-number x) scale)
525 (list (directed-round (car box) floor)
526 (directed-round (cadr box) floor)
527 (directed-round (max (1+ (car box)) (caddr box)) ceiling)
528 (directed-round (max (1+ (cadr box)) (cadddr box)) ceiling))))
530 (let* ((outputter (ly:make-paper-outputter
531 ;; FIXME: better wrap open/open-file,
532 ;; content-mangling is always bad.
533 ;; MINGW hack: need to have "b"inary for embedding CFFs
534 (open-file (format #f "~a.eps" filename) "wb")
536 (port (ly:outputter-port outputter))
537 (rounded-bbox (to-rounded-bp-box bbox))
538 (port (ly:outputter-port outputter))
539 (header (eps-header paper rounded-bbox load-fonts)))
540 (display header port)
541 (write-preamble paper load-fonts port)
542 (display "/mark_page_link { pop pop pop pop pop } bind def\n" port)
543 (display "gsave set-ps-scale-to-lily-scale\n" port)
544 (ly:outputter-dump-stencil outputter dump-me)
545 (display "stroke grestore\n%%Trailer\n%%EOF\n" port)
546 (ly:outputter-close outputter)))
548 (define (clip-systems-to-region basename paper systems region do-pdf do-png)
549 (let* ((extents-system-pairs
550 (filtered-map (lambda (paper-system)
551 (let* ((x-ext (system-clipped-x-extent
552 (paper-system-system-grob paper-system)
555 (cons x-ext paper-system)
560 (lambda (ext-system-pair)
561 (let* ((xext (car ext-system-pair))
562 (paper-system (cdr ext-system-pair))
563 (yext (paper-system-extent paper-system Y))
564 (bbox (list (car xext) (car yext)
565 (cdr xext) (cdr yext)))
566 (filename (if (< 0 count)
567 (format #f "~a-~a" basename count)
569 (set! count (1+ count))
570 (dump-stencil-as-EPS-with-bbox paper
571 (paper-system-stencil paper-system)
573 (ly:get-option 'include-eps-fonts)
576 (postscript->pdf 0 0 (format #f "~a.eps" filename)))
578 (postscript->png (ly:get-option 'resolution) 0 0
579 (format #f "~a.eps" filename)))))
580 extents-system-pairs)))
582 (define-public (clip-system-EPSes basename paper-book)
584 (member "pdf" (ly:output-formats)))
586 (member "png" (ly:output-formats)))
588 (define (clip-score-systems basename systems)
589 (let* ((layout (ly:grob-layout (paper-system-system-grob (car systems))))
590 (regions (ly:output-def-lookup layout 'clip-regions)))
593 (clip-systems-to-region
594 (format #f "~a-from-~a-to-~a-clip"
596 (rhythmic-location->file-string (car region))
597 (rhythmic-location->file-string (cdr region)))
598 layout systems region
602 ;; partition in system lists sharing their layout blocks
603 (let* ((systems (ly:paper-book-systems paper-book))
605 (score-system-list '()))
607 (lambda (system last-system)
608 (if (not (and last-system
609 (equal? (paper-system-layout last-system)
610 (paper-system-layout system))))
611 (set! score-system-list (cons '() score-system-list)))
612 (if (paper-system-layout system)
613 (set-car! score-system-list (cons system (car score-system-list))))
618 (for-each (lambda (system-list)
619 ;; filter out headers and top-level markup
620 (if (pair? system-list)
623 (format #f "~a-~a" basename count)
628 (define-public (output-preview-framework basename book scopes fields)
629 (let* ((paper (ly:paper-book-paper book))
630 (systems (relevant-book-systems book))
631 (to-dump-systems (relevant-dump-systems systems)))
632 (dump-stencil-as-EPS paper
633 (stack-stencils Y DOWN 0.0
634 (map paper-system-stencil
635 (reverse to-dump-systems)))
636 (format #f "~a.preview" basename)
638 (postprocess-output book framework-ps-module
639 (format #f "~a.preview.eps" basename)
640 (cons "png" (ly:output-formats)))))
642 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
644 (define (output-width-height defs)
645 (let* ((landscape (ly:output-def-lookup defs 'landscape))
646 (output-scale (ly:output-def-lookup defs 'output-scale))
648 (* x output-scale (/ (ly:bp 1)))))
649 (paper-width (convert (ly:output-def-lookup defs 'paper-width)))
650 (paper-height (convert (ly:output-def-lookup defs 'paper-height)))
651 (w (if landscape paper-height paper-width))
652 (h (if landscape paper-width paper-height)))
655 (define (output-resolution defs)
656 (let ((defs-resolution (ly:output-def-lookup defs 'pngresolution)))
657 (if (number? defs-resolution)
659 (ly:get-option 'resolution))))
661 (define (output-filename name)
662 (if (equal? (basename name ".ps") "-")
663 (string-append "./" name)
666 (define-public (convert-to-pdf book name)
667 (let* ((defs (ly:paper-book-paper book))
668 (width-height (output-width-height defs))
669 (width (car width-height))
670 (height (cdr width-height))
671 (filename (output-filename name)))
672 (postscript->pdf width height filename)))
674 (define-public (convert-to-png book name)
675 (let* ((defs (ly:paper-book-paper book))
676 (resolution (output-resolution defs))
677 (width-height (output-width-height defs))
678 (width (car width-height))
679 (height (cdr width-height))
680 (filename (output-filename name)))
681 (postscript->png resolution width height filename)))
683 (define-public (convert-to-ps book name)
686 (define-public (output-classic-framework basename book scopes fields)
687 (ly:error (_ "\nThe PostScript backend does not support the
688 system-by-system output. For that, use the EPS backend instead,
690 lilypond -dbackend=eps FILE
692 If have cut & pasted a lilypond fragment from a webpage, be sure
693 to only remove anything before
695 %% ****************************************************************
696 %% Start cut-&-pastable-section
697 %% ****************************************************************