Coverage Report

Created: 2024-03-18 06:28

/src/wxwidgets/include/wx/private/localeset.h
Line
Count
Source (jump to first uncovered line)
1
///////////////////////////////////////////////////////////////////////////////
2
// Name:        wx/private/localeset.h
3
// Purpose:     Define helper wxLocaleSetter class.
4
// Author:      Vadim Zeitlin
5
// Created:     2021-08-03 (extracted from tests/testprec.h)
6
// Copyright:   (c) 2021 Vadim Zeitlin <vadim@wxwidgets.org>
7
// Licence:     wxWindows licence
8
///////////////////////////////////////////////////////////////////////////////
9
10
#ifndef _WX_PRIVATE_LOCALESET_H_
11
#define _WX_PRIVATE_LOCALESET_H_
12
13
#include "wx/crt.h"     // wxStrdupA()
14
15
#include <locale.h>
16
17
// Helper class setting the locale to the given one for its lifetime.
18
class wxLocaleSetter
19
{
20
public:
21
    wxLocaleSetter(const char *loc)
22
        : m_locOld(wxStrdupA(setlocale(LC_ALL, nullptr)))
23
0
    {
24
0
        setlocale(LC_ALL, loc);
25
0
    }
26
27
    ~wxLocaleSetter()
28
0
    {
29
0
        setlocale(LC_ALL, m_locOld);
30
0
        free(m_locOld);
31
0
    }
32
33
private:
34
    char * const m_locOld;
35
36
    wxDECLARE_NO_COPY_CLASS(wxLocaleSetter);
37
};
38
39
// An even simpler helper for setting the locale to "C" one during its lifetime.
40
class wxCLocaleSetter : private wxLocaleSetter
41
{
42
public:
43
0
    wxCLocaleSetter() : wxLocaleSetter("C") { }
44
45
private:
46
    wxDECLARE_NO_COPY_CLASS(wxCLocaleSetter);
47
};
48
49
// This function must be called on program startup and after changing
50
// locale to ensure LC_CTYPE is set correctly under macOS (it does nothing
51
// under the other platforms currently).
52
inline void wxEnsureLocaleIsCompatibleWithCRT()
53
0
{
54
#if defined(__DARWIN__)
55
    // In OS X and iOS, wchar_t CRT functions convert to char* and fail under
56
    // some locales. The safest fix is to set LC_CTYPE to UTF-8 to ensure that
57
    // they can handle any input.
58
    //
59
    // Note that this must be done for any app, Cocoa or console, whether or
60
    // not it uses wxLocale.
61
    //
62
    // See https://stackoverflow.com/questions/11713745/why-does-the-printf-family-of-functions-care-about-locale
63
    setlocale(LC_CTYPE, "UTF-8");
64
#endif // defined(__DARWIN__)
65
0
}
66
67
#endif // _WX_PRIVATE_LOCALESET_H_