GrAutoLocaleSetter.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  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. #ifndef GrAutoLocaleSetter_DEFINED
  8. #define GrAutoLocaleSetter_DEFINED
  9. #include "include/gpu/GrTypes.h"
  10. #include "include/private/SkNoncopyable.h"
  11. #if defined(SK_BUILD_FOR_WIN)
  12. #include "include/core/SkString.h"
  13. #endif
  14. #if !defined(SK_BUILD_FOR_ANDROID)
  15. #include <locale.h>
  16. #endif
  17. #if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
  18. #include <xlocale.h>
  19. #include <cstring>
  20. #define HAVE_XLOCALE 1
  21. #else
  22. #define HAVE_XLOCALE 0
  23. #endif
  24. #if defined(SK_BUILD_FOR_ANDROID) || defined(__UCLIBC__) || defined(_NEWLIB_VERSION)
  25. #define HAVE_LOCALE_T 0
  26. #else
  27. #define HAVE_LOCALE_T 1
  28. #endif
  29. /**
  30. * Helper class for ensuring that we don't use the wrong locale when building shaders. Android
  31. * doesn't support locale in the NDK, so this is a no-op there.
  32. */
  33. class GrAutoLocaleSetter : public SkNoncopyable {
  34. public:
  35. GrAutoLocaleSetter (const char* name) {
  36. #if defined(SK_BUILD_FOR_WIN)
  37. fOldPerThreadLocale = _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
  38. char* oldLocale = setlocale(LC_ALL, name);
  39. if (oldLocale) {
  40. fOldLocale = oldLocale;
  41. fShouldRestoreLocale = true;
  42. } else {
  43. fShouldRestoreLocale = false;
  44. }
  45. #elif HAVE_LOCALE_T
  46. #if HAVE_XLOCALE
  47. // In xlocale nullptr means the C locale.
  48. if (0 == strcmp(name, "C")) {
  49. name = nullptr;
  50. }
  51. #endif
  52. fLocale = newlocale(LC_ALL_MASK, name, nullptr);
  53. if (fLocale) {
  54. fOldLocale = uselocale(fLocale);
  55. } else {
  56. fOldLocale = static_cast<locale_t>(nullptr);
  57. }
  58. #else
  59. (void) name; // suppress unused param warning.
  60. #endif
  61. }
  62. ~GrAutoLocaleSetter () {
  63. #if defined(SK_BUILD_FOR_WIN)
  64. if (fShouldRestoreLocale) {
  65. setlocale(LC_ALL, fOldLocale.c_str());
  66. }
  67. _configthreadlocale(fOldPerThreadLocale);
  68. #elif HAVE_LOCALE_T
  69. if (fLocale) {
  70. uselocale(fOldLocale);
  71. freelocale(fLocale);
  72. }
  73. #endif
  74. }
  75. private:
  76. #if defined(SK_BUILD_FOR_WIN)
  77. int fOldPerThreadLocale;
  78. bool fShouldRestoreLocale;
  79. SkString fOldLocale;
  80. #elif HAVE_LOCALE_T
  81. locale_t fOldLocale;
  82. locale_t fLocale;
  83. #endif
  84. };
  85. #undef HAVE_LOCALE_T
  86. #undef HAVE_XLOCALE
  87. #endif