]> git.donarmstrong.com Git - lilypond.git/blob - lily/pdf-scheme.cc
pdf-metadata: Use UTF-16BE for metadata if required
[lilypond.git] / lily / pdf-scheme.cc
1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3
4   Copyright (C) 2011 Reinhold Kainhofer <reinhold@kainhofer.com>
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 #include <glib.h>
21 using namespace std;
22
23 #include "lily-guile.hh"
24
25
26 LY_DEFINE (ly_encode_string_for_pdf, "ly:encode-string-for-pdf",
27            1, 0, 0, (SCM str),
28            "Check whether the string needs to be encoded for PDF output (Latin1,"
29            " PDFDocEncoding or in the most general case UTF-16BE).")
30 {
31   LY_ASSERT_TYPE (scm_is_string, str, 1);
32   char *p = ly_scm2str0 (str);
33   char *g = NULL;
34   const char *charset;
35   gsize bytes_written = 0;
36   g_get_charset (&charset); /* The current locale */
37
38   /* First, try to convert to ISO-8859-1 (no encodings required) */
39   g = g_convert (p, -1, "ISO-8859-1", charset, 0, &bytes_written, 0);
40   /* If that fails, we have to resolve to full UTF-16BE */
41   if (!g) {
42     char *g_without_BOM = g_convert (p, -1,  "UTF-16BE", charset, 0, &bytes_written, 0);
43     /* prepend the BOM manually, g_convert doesn't do it! */
44     g = new char[bytes_written+3];
45     g[0] = (char)254;
46     g[1] = (char)255;
47     memcpy (&g[2], g_without_BOM, bytes_written+1); // Copy string + \0
48     free (g_without_BOM);
49     bytes_written += 2;
50   }
51   free (p);
52
53   /* Convert back to SCM object and return it */
54   if (g) {
55     return scm_from_locale_stringn (g, bytes_written);
56   } else {
57     return str;
58   }
59
60 }