]> git.donarmstrong.com Git - lilypond.git/blob - scm/backend-library.scm
Issue 4374 / 2: Add make-tmpfile procedure
[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 name)
59   (let* ((pdf-name (string-append
60                     (dir-basename name ".ps" ".eps")
61                     ".pdf"))
62          (is-eps (string-match "\\.eps$" name))
63          (*unspecified* (if #f #f))
64          (cmd
65           (remove (lambda (x) (eq? x *unspecified*))
66                   (list
67                    (search-gs)
68                    (if (ly:get-option 'verbose) *unspecified* "-q")
69                    (if (or (ly:get-option 'gs-load-fonts)
70                            (ly:get-option 'gs-load-lily-fonts)
71                            (eq? PLATFORM 'windows))
72                        "-dNOSAFER"
73                        "-dSAFER")
74
75                    (if is-eps
76                        "-dEPSCrop"
77                        (ly:format "-dDEVICEWIDTHPOINTS=~$" paper-width))
78                    (if is-eps
79                        *unspecified*
80                        (ly:format "-dDEVICEHEIGHTPOINTS=~$" paper-height))
81                    "-dCompatibilityLevel=1.4"
82                    "-dNOPAUSE"
83                    "-dBATCH"
84                    "-r1200"
85                    (if (ly:bigpdfs) "-dSubsetFonts=false")
86                    "-sDEVICE=pdfwrite"
87                    (string-append "-sOutputFile="
88                                   (string-join
89                                    (string-split pdf-name #\%)
90                                    "%%"))
91                    "-c.setpdfwrite"
92                    (string-append "-f" name)))))
93
94     (ly:message (_ "Converting to `~a'...\n") pdf-name)
95     (ly:system cmd)))
96
97 (define-public (postscript->png resolution paper-width paper-height name)
98   (let* ((verbose (ly:get-option 'verbose))
99          (rename-page-1 #f))
100
101     ;; Do not try to guess the name of the png file,
102     ;; GS produces PNG files like BASE-page%d.png.
103     (ly:message (_ "Converting to ~a...") "PNG")
104     (make-ps-images name
105                     #:resolution resolution
106                     #:page-width paper-width
107                     #:page-height paper-height
108                     #:rename-page-1 rename-page-1
109                     #:be-verbose verbose
110                     #:anti-alias-factor (ly:get-option 'anti-alias-factor)
111                     #:pixmap-format (ly:get-option 'pixmap-format))
112     (ly:progress "\n")))
113
114 (define-public (make-tmpfile)
115   (let* ((tmpl
116           (string-append (cond
117                           ;; MINGW hack: TMP / TEMP may include
118                           ;; unusable characters (Unicode etc.).
119                           ((eq? PLATFORM 'windows) "./tmp-")
120                           ;; Cygwin can handle any characters
121                           ;; including Unicode.
122                           ((eq? PLATFORM 'cygwin) (string-append
123                                                    (or (getenv "TMP")
124                                                        (getenv "TEMP"))
125                                                    "/"))
126                           ;; Other platforms (POSIX platforms)
127                           ;; use TMPDIR or /tmp.
128                           (else (string-append
129                                  (or (getenv "TMPDIR")
130                                      "/tmp")
131                                  "/")))
132                           "lilypond-XXXXXX"))
133          (port-tmp (mkstemp! tmpl)))
134     (if (eq? PLATFORM 'windows)
135         ;; MINGW hack: MinGW Guile's mkstemp! is broken.
136         ;; It creates a file by the text mode instead of the binary mode.
137         ;; (It is fixed from Guile 2.0.9.)
138         ;; We need the binary mode for embeddings CFFs.
139         ;; So, we re-open the same file by the binary mode.
140         (let* ((filename (port-filename port-tmp))
141                (port (open-file filename "r+b")))
142           (close port-tmp)
143           port)
144         ;; Cygwin and other platforms:
145         ;; Pass through the return value of mkstemp!
146         port-tmp)))
147
148 (define-public (postprocess-output paper-book module filename formats)
149   (let* ((completed (completize-formats formats))
150          (base (dir-basename filename ".ps" ".eps"))
151          (intermediate (remove (lambda (x) (member x formats)) completed)))
152     (for-each (lambda (f)
153                 ((eval (string->symbol (format #f "convert-to-~a" f))
154                        module) paper-book filename)) completed)
155     (if (ly:get-option 'delete-intermediate-files)
156         (for-each (lambda (f)
157                     (if (file-exists? f) (delete-file f)))
158                   (map (lambda (x) (string-append base "." x)) intermediate)))))
159
160 (define-public (completize-formats formats)
161   (define new-fmts '())
162   (if (member "png" formats)
163       (set! formats (cons "ps" formats)))
164   (if (member "pdf" formats)
165       (set! formats (cons "ps" formats)))
166   (for-each (lambda (x)
167               (if (member x formats) (set! new-fmts (cons x new-fmts))))
168             '("ps" "pdf" "png"))
169   (uniq-list (reverse new-fmts)))
170
171 (define (header-to-file file-name key value)
172   (set! key (symbol->string key))
173   (if (not (equal? "-" file-name))
174       (set! file-name (string-append file-name "." key)))
175   (ly:message (_ "Writing header field `~a' to `~a'...")
176               key
177               (if (equal? "-" file-name) "<stdout>" file-name))
178   (if (equal? file-name "-")
179       (display value)
180       (let ((port (open-file file-name "w")))
181         (display value port)
182         (close-port port)))
183
184   (ly:progress "\n")
185   "")
186
187 (define-public (output-scopes scopes fields basename)
188   (define (output-scope scope)
189     (string-concatenate
190      (module-map
191       (lambda (sym var)
192         (let ((val (if (variable-bound? var) (variable-ref var) "")))
193           (if (and (memq sym fields) (string? val))
194               (header-to-file basename sym val))
195           ""))
196       scope)))
197   (string-concatenate (map output-scope scopes)))
198
199 (define-public (relevant-book-systems book)
200   (let ((systems (ly:paper-book-systems book)))
201     ;; skip booktitles.
202     (if (and (not (ly:get-option 'include-book-title-preview))
203              (pair? systems)
204              (ly:prob-property (car systems) 'is-book-title #f))
205         (cdr systems)
206         systems)))
207
208 (define-public (relevant-dump-systems systems)
209   (let ((to-dump-systems '()))
210     (for-each
211      (lambda (sys)
212        (if (or (paper-system-title? sys)
213                (not (pair? to-dump-systems))
214                (paper-system-title? (car to-dump-systems)))
215            (set! to-dump-systems (cons sys to-dump-systems))))
216      systems)
217     to-dump-systems))
218
219 (define missing-stencil-list '())
220
221 (define-public (backend-testing output-module)
222   (define (missing-stencil-expression name)
223     (begin
224       (ly:warning (_ "missing stencil expression `~S'") name)
225       ""))
226
227   (for-each (lambda (x)
228               (if (not (module-defined? output-module x))
229                   (begin
230                     (module-define! output-module x
231                                     (lambda* (#:optional y . z)
232                                              (missing-stencil-expression x)))
233                     (set! missing-stencil-list (cons x missing-stencil-list)))))
234             (ly:all-stencil-commands)))
235
236 (define-public (remove-stencil-warnings output-module)
237   (for-each
238    (lambda (x)
239      (module-remove! output-module x))
240    missing-stencil-list))
241
242 (define (filter-out pred? lst)
243   (filter (lambda (x) (not (pred? x))) lst))
244
245 (define-public (font-name-split font-name)
246   "Return @code{(FONT-NAME . DESIGN-SIZE)} from @var{font-name} string
247 or @code{#f}."
248   (let ((match (regexp-exec (make-regexp "(.*)-([0-9]*)") font-name)))
249     (if (regexp-match? match)
250         (cons (match:substring match 1) (match:substring match 2))
251         (cons font-name-designsize #f))))
252
253 ;; Example of a pango-physical-font
254 ;; ("Emmentaler-11" "/home/janneke/vc/lilypond/out/share/lilypond/current/fonts/otf/emmentaler-11.otf" 0)
255 (define-public (pango-pf-font-name pango-pf)
256   "Return the font-name of the pango physical font @var{pango-pf}."
257   (list-ref pango-pf 0))
258 (define-public (pango-pf-file-name pango-pf)
259   "Return the file-name of the pango physical font @var{pango-pf}."
260   (list-ref pango-pf 1))
261 (define-public (pango-pf-fontindex pango-pf)
262   "Return the fontindex of the pango physical font @var{pango-pf}."
263   (list-ref pango-pf 2))
264
265 (define (pango-font-name pango-font)
266   (let ((pf-fonts (ly:pango-font-physical-fonts pango-font)))
267     (if (pair? pf-fonts)
268         (pango-pf-font-name (car pf-fonts))
269         "")))
270
271 (define-public (define-fonts paper define-font define-pango-pf)
272   "Return a string of all fonts used in @var{paper}, invoking the functions
273 @var{define-font} and @var{define-pango-pf} for producing the actual font
274 definition."
275
276   (let* ((font-list (ly:paper-fonts paper))
277          (pango-fonts (filter ly:pango-font? font-list))
278          (other-fonts (filter-out ly:pango-font? font-list))
279          (other-font-names (map ly:font-name other-fonts))
280          (pango-only-fonts
281           (filter-out (lambda (x)
282                         (member (pango-font-name x) other-font-names))
283                       pango-fonts)))
284
285     (define (font-load-command font)
286       (let* ((font-name (ly:font-name font))
287              (designsize (ly:font-design-size font))
288              (magnification (* (ly:font-magnification font)))
289              (ops (ly:output-def-lookup paper 'output-scale))
290              (scaling (* ops magnification designsize)))
291         (if (equal? font-name "unknown")
292             (display (list font font-name)))
293         (define-font font font-name scaling)))
294
295     (define (pango-font-load-command pango-font)
296       (let* ((pf-fonts (ly:pango-font-physical-fonts pango-font))
297              (pango-pf (if (pair? pf-fonts) (car pf-fonts) '("" "" 0)))
298              (font-name (pango-pf-font-name pango-pf))
299              (scaling (ly:output-def-lookup paper 'output-scale)))
300         (if (equal? font-name "unknown")
301             (display (list pango-font font-name)))
302         (define-pango-pf pango-pf font-name scaling)))
303
304     (string-append
305      (string-concatenate (map font-load-command other-fonts))
306      (string-concatenate (map pango-font-load-command pango-only-fonts)))))