I18n.hpp
1 #ifndef CPP3DS_I18N_HPP
2 #define CPP3DS_I18N_HPP
3 
4 #ifndef EMULATION
5 #include <3ds.h>
6 #endif
7 #include <iostream>
8 #include <stdio.h>
9 #include <map>
10 #include <cstring>
11 #include <memory>
12 #include <cpp3ds/System/String.hpp>
13 
14 #define _(key, ...) (cpp3ds::I18n::getInstance().translate(key, ##__VA_ARGS__))
15 
16 
17 namespace {
18 
19  template<typename ... Args>
20  cpp3ds::String string_format( const std::string& format, Args ... args )
21  {
22  size_t size = snprintf( nullptr, 0, format.c_str(), args ... ) + 1; // Extra space for '\0'
23  std::unique_ptr<char[]> buf( new char[ size ] );
24  snprintf( buf.get(), size, format.c_str(), args ... );
25  std::string stringUtf8( buf.get(), buf.get() + size - 1 ); // We don't want the '\0' inside
26  std::wstring stringUtf32;
27  cpp3ds::Utf8::toUtf32(stringUtf8.begin(), stringUtf8.end(), std::back_inserter(stringUtf32));
28  return cpp3ds::String(stringUtf32);
29  }
30 }
31 
32 
33 namespace cpp3ds {
34 
35 enum Language {
36  Japanese = 0,
37  English = 1,
38  French,
39  German,
40  Italian,
41  Spanish,
42  ChineseSimplified,
43  Korean,
44  Dutch,
45  Portuguese,
46  Russian,
47  ChineseTraditional,
48 };
49 
50 class I18n {
51 public:
52 
53  static I18n& getInstance();
54 
55  static void loadLanguage(Language language);
56 
57  static inline void loadLanguageFile(const std::string& filename);
58 
59  static Language getLanguage();
60 
61  template<typename ... Args>
62  const String translate(const char* key, Args ... args) const {
63  std::string trans;
64  TranslationMap::const_iterator it = m_content.find(key);
65  if (it == m_content.end())
66  trans = std::string(key);
67  else
68  trans = it->second;
69  return string_format(trans, args ...);
70  }
71 
72  template<typename ... Args>
73  const String translate(const std::string& key, Args ... args) const {
74  return translate(key.c_str(), args ...);
75  }
76 
77  const std::string getLangString(const Language language) const;
78 
79 private:
80  I18n();
81 
82  I18n(const I18n &);
83 
84  bool loadFromFile(const std::string filename);
85 
86  bool loadFromLanguage(const Language language);
87 
88  typedef std::map <std::string, std::string> TranslationMap;
89  TranslationMap m_content;
90  Language m_language;
91 };
92 
93 } // namespace cpp3ds
94 
95 #endif // CPP3DS_I18N_HPP
96 
97 
101 ////////////////////////////////////////////////////////////
Utility string class that automatically handles conversions between types and encodings.
Definition: String.hpp:42
static Out toUtf32(In begin, In end, Out output)
Convert a UTF-8 characters range to UTF-32.