minor comment change
[ardour.git] / libs / pbd / locale_guard.cc
1 /*
2     Copyright (C) 2012 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <stdlib.h>
21 #include <string.h>
22 #include <assert.h>
23 #include <locale.h>
24
25 #include "pbd/locale_guard.h"
26
27 using namespace PBD;
28
29 /* The initial C++ locale is "C" regardless of the user's preferred locale.
30  * and affects std::sprintf() et al from <cstdio>
31  *
32  * the C locale from setlocale() matches the user's preferred locale
33  * and effects ::sprintf() et al from <stdio.h>
34  *
35  * Setting the C++ locale will change the C locale, but not the other way 'round.
36  * and some plugin may change either behind our back.
37  */
38
39 LocaleGuard::LocaleGuard (const char*)
40         : old_c (0)
41 {
42         init ();
43 }
44
45 LocaleGuard::LocaleGuard ()
46         : old_c (0)
47 {
48         init ();
49 }
50
51 void
52 LocaleGuard::init ()
53 {
54         char* actual = setlocale (LC_NUMERIC, NULL);
55         if (strcmp ("C", actual)) {
56                 /* purpose of LocaleGuard is to make sure we're using "C" for
57                    the numeric locale during its lifetime, so make it so.
58                 */
59                 old_c = strdup (actual);
60                 /* this changes both C++ and C locale */
61                 std::locale::global (std::locale (std::locale::classic(), "C", std::locale::numeric));
62         }
63         assert (old_cpp == std::locale::classic ());
64 }
65
66 LocaleGuard::~LocaleGuard ()
67 {
68         char* actual = setlocale (LC_NUMERIC, NULL);
69         std::locale current;
70
71         if (current != old_cpp) {
72                 /* the C++ locale should always be "C", that's the default
73                  * at application start, and ardour never changes it to
74                  * anything but "C".
75                  *
76                  * if it's not: some plugin meddled with it.
77                  */
78                 assert (old_cpp == std::locale::classic ());
79                 std::locale::global (old_cpp);
80         }
81         if (old_c && strcmp (old_c, actual)) {
82                 setlocale (LC_NUMERIC, old_c);
83         }
84         free (old_c);
85 }