blob: 564abd917f1b4973ebad7211b8d0ce7bda0378cc [file] [log] [blame]
bsalomon6f7f2012015-03-16 14:00:52 -07001/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#ifndef GrAutoLocaleSetter_DEFINED
9#define GrAutoLocaleSetter_DEFINED
10
11#include "GrTypes.h"
12
kkinnunenaab16e52015-12-13 23:12:31 -080013#if defined(SK_BUILD_FOR_WIN)
14#include "SkString.h"
15#endif
16
bsalomon6f7f2012015-03-16 14:00:52 -070017#if !defined(SK_BUILD_FOR_ANDROID)
18#include <locale.h>
19#endif
20
21#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
22#include <xlocale.h>
23#endif
24
smkleindb284c52015-12-15 10:52:51 -080025#if defined(SK_BUILD_FOR_ANDROID) || defined(__UCLIBC__) || defined(_NEWLIB_VERSION)
26#define HAVE_LOCALE_T 0
27#else
28#define HAVE_LOCALE_T 1
29#endif
30
bsalomon6f7f2012015-03-16 14:00:52 -070031/**
32 * Helper class for ensuring that we don't use the wrong locale when building shaders. Android
33 * doesn't support locale in the NDK, so this is a no-op there.
34 */
kkinnunen4222e192015-11-19 08:45:30 -080035class GrAutoLocaleSetter : public SkNoncopyable {
bsalomon6f7f2012015-03-16 14:00:52 -070036public:
37 GrAutoLocaleSetter (const char* name) {
38#if defined(SK_BUILD_FOR_WIN)
halcanary9d524f22016-03-29 09:03:52 -070039 fOldPerThreadLocale = _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
kkinnunenaab16e52015-12-13 23:12:31 -080040 char* oldLocale = setlocale(LC_ALL, name);
41 if (oldLocale) {
42 fOldLocale = oldLocale;
43 fShouldRestoreLocale = true;
44 } else {
45 fShouldRestoreLocale = false;
46 }
smkleindb284c52015-12-15 10:52:51 -080047#elif HAVE_LOCALE_T
bsalomon6f7f2012015-03-16 14:00:52 -070048 fLocale = newlocale(LC_ALL, name, 0);
49 if (fLocale) {
50 fOldLocale = uselocale(fLocale);
kkinnunen4222e192015-11-19 08:45:30 -080051 } else {
52 fOldLocale = static_cast<locale_t>(0);
bsalomon6f7f2012015-03-16 14:00:52 -070053 }
54#else
55 (void) name; // suppress unused param warning.
56#endif
57 }
58
59 ~GrAutoLocaleSetter () {
60#if defined(SK_BUILD_FOR_WIN)
kkinnunenaab16e52015-12-13 23:12:31 -080061 if (fShouldRestoreLocale) {
62 setlocale(LC_ALL, fOldLocale.c_str());
bsalomonea750532015-12-04 07:27:36 -080063 }
bsalomon6f7f2012015-03-16 14:00:52 -070064 _configthreadlocale(fOldPerThreadLocale);
smkleindb284c52015-12-15 10:52:51 -080065#elif HAVE_LOCALE_T
bsalomon6f7f2012015-03-16 14:00:52 -070066 if (fLocale) {
67 uselocale(fOldLocale);
68 freelocale(fLocale);
69 }
70#endif
71 }
72
73private:
74#if defined(SK_BUILD_FOR_WIN)
75 int fOldPerThreadLocale;
kkinnunenaab16e52015-12-13 23:12:31 -080076 bool fShouldRestoreLocale;
77 SkString fOldLocale;
smkleindb284c52015-12-15 10:52:51 -080078#elif HAVE_LOCALE_T
bsalomon6f7f2012015-03-16 14:00:52 -070079 locale_t fOldLocale;
80 locale_t fLocale;
81#endif
82};
83
smkleindb284c52015-12-15 10:52:51 -080084#undef HAVE_LOCALE_T
85
bsalomon6f7f2012015-03-16 14:00:52 -070086#endif