]> git.donarmstrong.com Git - lilypond.git/blob - scm/backend-library.scm
Issue 4374 / 4: Use mkstemp for intermediate ps files
[lilypond.git] / scm / backend-library.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 2005--2015 Jan Nieuwenhuizen <janneke@gnu.org>
4 ;;;; Han-Wen Nienhuys <hanwen@xs4all.nl>
5 ;;;;
6 ;;;; LilyPond is free software: you can redistribute it and/or modify
7 ;;;; it under the terms of the GNU General Public License as published by
8 ;;;; the Free Software Foundation, either version 3 of the License, or
9 ;;;; (at your option) any later version.
10 ;;;;
11 ;;;; LilyPond is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 ;;;; GNU General Public License for more details.
15 ;;;;
16 ;;;; You should have received a copy of the GNU General Public License
17 ;;;; along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
18
19 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
20 ;; backend helpers.
21
22 (use-modules (scm ps-to-png)
23              (scm paper-system)
24              (ice-9 optargs))
25
26 (define-public (ly:system command)
27   (ly:debug (_ "Invoking `~a'...") (string-join command))
28   (let ((status (apply ly:spawn command)))
29     (if (> status 0)
30         (begin
31           (ly:warning (_ "`~a' failed (~a)\n") command status)
32           ;; hmmm.  what's the best failure option?
33           (throw 'ly-file-failed)))))
34
35 (define-public (sanitize-command-option str)
36   "Kill dubious shell quoting."
37
38   (string-append
39    "\""
40    (regexp-substitute/global #f "[^-_ 0-9,.a-zA-Z'\"\\]" str 'pre 'post)
41    "\""))
42
43 (define-public (search-executable names)
44   (define (helper path lst)
45     (if (null? (cdr lst))
46         (car lst)
47         (if (search-path path (car lst)) (car lst)
48             (helper path (cdr lst)))))
49
50   (let ((path (parse-path (getenv "PATH"))))
51     (helper path names)))
52
53 (define-public (search-gs)
54
55   ;; must be sure that we don't catch stuff from old GUBs.
56   (search-executable '("gs")))
57
58 (define-public (postscript->pdf paper-width paper-height
59                                 base-name tmp-name is-eps)
60   (let* ((pdf-name (string-append base-name ".pdf"))
61          (*unspecified* (if #f #f))
62          (cmd
63           (remove (lambda (x) (eq? x *unspecified*))
64                   (list
65                    (search-gs)
66                    (if (ly:get-option 'verbose) *unspecified* "-q")
67                    (if (or (ly:get-option 'gs-load-fonts)
68                            (ly:get-option 'gs-load-lily-fonts)
69                            (eq? PLATFORM 'windows))
70                        "-dNOSAFER"
71                        "-dSAFER")
72
73                    (if is-eps
74                        "-dEPSCrop"
75                        (ly:format "-dDEVICEWIDTHPOINTS=~$" paper-width))
76                    (if is-eps
77                        *unspecified*
78                        (ly:format "-dDEVICEHEIGHTPOINTS=~$" paper-height))
79                    "-dCompatibilityLevel=1.4"
80                    "-dNOPAUSE"
81                    "-dBATCH"
82                    "-r1200"
83                    (if (ly:bigpdfs) "-dSubsetFonts=false")
84                    "-sDEVICE=pdfwrite"
85                    (string-append "-sOutputFile="
86                                   (string-join
87                                    (string-split pdf-name #\%)
88                                    "%%"))
89                    "-c.setpdfwrite"
90                    (string-append "-f" tmp-name)))))
91
92     (ly:message (_ "Converting to `~a'...\n") pdf-name)
93     (ly:system cmd)))
94
95 (define-public (postscript->png resolution paper-width paper-height
96                                 base-name tmp-name is-eps)
97   (let* ((verbose (ly:get-option 'verbose))
98          (rename-page-1 #f))
99
100     ;; Do not try to guess the name of the png file,
101     ;; GS produces PNG files like BASE-page%d.png.
102     (ly:message (_ "Converting to ~a...") "PNG")
103     (make-ps-images base-name tmp-name is-eps
104                     #:resolution resolution
105                     #:page-width paper-width
106                     #:page-height paper-height
107                     #:rename-page-1 rename-page-1
108                     #:be-verbose verbose
109                     #:anti-alias-factor (ly:get-option 'anti-alias-factor)
110                     #:pixmap-format (ly:get-option 'pixmap-format))
111     (ly:progress "\n")))
112
113 (define-public (postscript->ps base-name tmp-name is-eps)
114   (let* ((ps-name (string-append base-name
115                                  (if is-eps ".eps" ".ps"))))
116     (if (not (equal? ps-name tmp-name))
117         (begin
118           (ly:message (_ "Copying to `~a'...\n") ps-name)
119           (copy-binary-file tmp-name ps-name)))))
120
121 (define-public (copy-binary-file from-name to-name)
122   (if (eq? PLATFORM 'windows)
123       ;; MINGW hack: MinGW Guile's copy-file is broken.
124       ;; It opens files by the text mode instead of the binary mode.
125       ;; (It is fixed from Guile 2.0.9.)
126       ;; By the text mode, copied binary files are broken.
127       ;; So, we open files by the binary mode and copy by ourselves.
128       (let ((port-from (open-file from-name "rb"))
129             (port-to (open-file to-name "wb")))
130         (let loop((c (read-char port-from)))
131           (if (eof-object? c)
132               (begin (close port-from)
133                      (close port-to))
134               (begin (write-char c port-to)
135                      (loop (read-char port-from))))))
136       ;; Cygwin and other platforms:
137       ;; Pass through to copy-file
138       (copy-file from-name to-name)))
139
140 (define-public (make-tmpfile)
141   (let* ((tmpl
142           (string-append (cond
143                           ;; MINGW hack: TMP / TEMP may include
144                           ;; unusable characters (Unicode etc.).
145                           ((eq? PLATFORM 'windows) "./tmp-")
146                           ;; Cygwin can handle any characters
147                           ;; including Unicode.
148                           ((eq? PLATFORM 'cygwin) (string-append
149                                                    (or (getenv "TMP")
150                                                        (getenv "TEMP"))
151                                                    "/"))
152                           ;; Other platforms (POSIX platforms)
153                           ;; use TMPDIR or /tmp.
154                           (else (string-append
155                                  (or (getenv "TMPDIR")
156                                      "/tmp")
157                                  "/")))
158                           "lilypond-XXXXXX"))
159          (port-tmp (mkstemp! tmpl)))
160     (if (eq? PLATFORM 'windows)
161         ;; MINGW hack: MinGW Guile's mkstemp! is broken.
162         ;; It creates a file by the text mode instead of the binary mode.
163         ;; (It is fixed from Guile 2.0.9.)
164         ;; We need the binary mode for embeddings CFFs.
165         ;; So, we re-open the same file by the binary mode.
166         (let* ((filename (port-filename port-tmp))
167                (port (open-file filename "r+b")))
168           (close port-tmp)
169           port)
170         ;; Cygwin and other platforms:
171         ;; Pass through the return value of mkstemp!
172         port-tmp)))
173
174 (define-public (postprocess-output paper-book module formats
175                                    base-name tmp-name is-eps)
176   (let* ((completed (completize-formats formats is-eps)))
177     (for-each (lambda (f)
178                 ((eval (string->symbol (format #f "convert-to-~a" f)) module)
179                  paper-book base-name tmp-name is-eps)) completed)
180     (if (and (ly:get-option 'delete-intermediate-files)
181              (or (not is-eps)
182                  (not (member "ps" completed)))
183              (file-exists? tmp-name))
184         (begin (ly:message (_ "Deleting `~a'...\n") tmp-name)
185                (delete-file tmp-name)))))
186
187 (define-public (completize-formats formats is-eps)
188   (define new-fmts '())
189   (if (and is-eps (member "eps" formats))
190       (set! formats (cons "ps" formats)))
191   (if (not (or (member "pdf" formats)
192                (member "png" formats)))
193       (set! formats (cons "ps" formats)))
194   (for-each (lambda (x)
195               (if (member x formats) (set! new-fmts (cons x new-fmts))))
196             '("ps" "pdf" "png"))
197   (uniq-list (reverse new-fmts)))
198
199 (define (header-to-file file-name key value)
200   (set! key (symbol->string key))
201   (if (not (equal? "-" file-name))
202       (set! file-name (string-append file-name "." key)))
203   (ly:message (_ "Writing header field `~a' to `~a'...")
204               key
205               (if (equal? "-" file-name) "<stdout>" file-name))
206   (if (equal? file-name "-")
207       (display value)
208       (let ((port (open-file file-name "w")))
209         (display value port)
210         (close-port port)))
211
212   (ly:progress "\n")
213   "")
214
215 (define-public (output-scopes scopes fields basename)
216   (define (output-scope scope)
217     (string-concatenate
218      (module-map
219       (lambda (sym var)
220         (let ((val (if (variable-bound? var) (variable-ref var) "")))
221           (if (and (memq sym fields) (string? val))
222               (header-to-file basename sym val))
223           ""))
224       scope)))
225   (string-concatenate (map output-scope scopes)))
226
227 (define-public (relevant-book-systems book)
228   (let ((systems (ly:paper-book-systems book)))
229     ;; skip booktitles.
230     (if (and (not (ly:get-option 'include-book-title-preview))
231              (pair? systems)
232              (ly:prob-property (car systems) 'is-book-title #f))
233         (cdr systems)
234         systems)))
235
236 (define-public (relevant-dump-systems systems)
237   (let ((to-dump-systems '()))
238     (for-each
239      (lambda (sys)
240        (if (or (paper-system-title? sys)
241                (not (pair? to-dump-systems))
242                (paper-system-title? (car to-dump-systems)))
243            (set! to-dump-systems (cons sys to-dump-systems))))
244      systems)
245     to-dump-systems))
246
247 (define missing-stencil-list '())
248
249 (define-public (backend-testing output-module)
250   (define (missing-stencil-expression name)
251     (begin
252       (ly:warning (_ "missing stencil expression `~S'") name)
253       ""))
254
255   (for-each (lambda (x)
256               (if (not (module-defined? output-module x))
257                   (begin
258                     (module-define! output-module x
259                                     (lambda* (#:optional y . z)
260                                              (missing-stencil-expression x)))
261                     (set! missing-stencil-list (cons x missing-stencil-list)))))
262             (ly:all-stencil-commands)))
263
264 (define-public (remove-stencil-warnings output-module)
265   (for-each
266    (lambda (x)
267      (module-remove! output-module x))
268    missing-stencil-list))
269
270 (define (filter-out pred? lst)
271   (filter (lambda (x) (not (pred? x))) lst))
272
273 (define-public (font-name-split font-name)
274   "Return @code{(FONT-NAME . DESIGN-SIZE)} from @var{font-name} string
275 or @code{#f}."
276   (let ((match (regexp-exec (make-regexp "(.*)-([0-9]*)") font-name)))
277     (if (regexp-match? match)
278         (cons (match:substring match 1) (match:substring match 2))
279         (cons font-name-designsize #f))))
280
281 ;; Example of a pango-physical-font
282 ;; ("Emmentaler-11" "/home/janneke/vc/lilypond/out/share/lilypond/current/fonts/otf/emmentaler-11.otf" 0)
283 (define-public (pango-pf-font-name pango-pf)
284   "Return the font-name of the pango physical font @var{pango-pf}."
285   (list-ref pango-pf 0))
286 (define-public (pango-pf-file-name pango-pf)
287   "Return the file-name of the pango physical font @var{pango-pf}."
288   (list-ref pango-pf 1))
289 (define-public (pango-pf-fontindex pango-pf)
290   "Return the fontindex of the pango physical font @var{pango-pf}."
291   (list-ref pango-pf 2))
292
293 (define (pango-font-name pango-font)
294   (let ((pf-fonts (ly:pango-font-physical-fonts pango-font)))
295     (if (pair? pf-fonts)
296         (pango-pf-font-name (car pf-fonts))
297         "")))
298
299 (define-public (define-fonts paper define-font define-pango-pf)
300   "Return a string of all fonts used in @var{paper}, invoking the functions
301 @var{define-font} and @var{define-pango-pf} for producing the actual font
302 definition."
303
304   (let* ((font-list (ly:paper-fonts paper))
305          (pango-fonts (filter ly:pango-font? font-list))
306          (other-fonts (filter-out ly:pango-font? font-list))
307          (other-font-names (map ly:font-name other-fonts))
308          (pango-only-fonts
309           (filter-out (lambda (x)
310                         (member (pango-font-name x) other-font-names))
311                       pango-fonts)))
312
313     (define (font-load-command font)
314       (let* ((font-name (ly:font-name font))
315              (designsize (ly:font-design-size font))
316              (magnification (* (ly:font-magnification font)))
317              (ops (ly:output-def-lookup paper 'output-scale))
318              (scaling (* ops magnification designsize)))
319         (if (equal? font-name "unknown")
320             (display (list font font-name)))
321         (define-font font font-name scaling)))
322
323     (define (pango-font-load-command pango-font)
324       (let* ((pf-fonts (ly:pango-font-physical-fonts pango-font))
325              (pango-pf (if (pair? pf-fonts) (car pf-fonts) '("" "" 0)))
326              (font-name (pango-pf-font-name pango-pf))
327              (scaling (ly:output-def-lookup paper 'output-scale)))
328         (if (equal? font-name "unknown")
329             (display (list pango-font font-name)))
330         (define-pango-pf pango-pf font-name scaling)))
331
332     (string-append
333      (string-concatenate (map font-load-command other-fonts))
334      (string-concatenate (map pango-font-load-command pango-only-fonts)))))