AppLang.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //
  2. // AppLang.cpp
  3. // Simulator
  4. //
  5. #include "AppLang.h"
  6. USING_NS_CC;
  7. AppLang::AppLang()
  8. : _hasInit(false),
  9. _localizationFileName("lang")
  10. {
  11. }
  12. void AppLang::readLocalizationFile()
  13. {
  14. if (!_hasInit)
  15. {
  16. _hasInit = true;
  17. auto fileUtils = FileUtils::getInstance();
  18. if (!fileUtils->isFileExist(_localizationFileName))
  19. {
  20. cocos2d::log("[WARNING]:not find %s", _localizationFileName.c_str());
  21. return;
  22. }
  23. auto fullFilePath = fileUtils->fullPathForFilename(_localizationFileName);
  24. std::string fileContent = FileUtils::getInstance()->getStringFromFile(fullFilePath);
  25. if(fileContent.empty())
  26. return;
  27. if (_docRootjson.Parse<0>(fileContent.c_str()).HasParseError())
  28. {
  29. cocos2d::log("[WARNING]:read json file %s failed because of %d", _localizationFileName.c_str(), _docRootjson.GetParseError());
  30. return;
  31. }
  32. }
  33. }
  34. AppLang* AppLang::getInstance()
  35. {
  36. static AppLang *lang = nullptr;
  37. if (!lang)
  38. {
  39. lang = new AppLang;
  40. lang->readLocalizationFile();
  41. }
  42. return lang;
  43. }
  44. std::string AppLang::getString(const std::string &lang, const std::string &key)
  45. {
  46. std::string tmpKey = key;
  47. const char *ckey = tmpKey.c_str();
  48. std::string tmpLang = lang;
  49. const char *langKey = tmpLang.c_str();
  50. if (!_docRootjson.IsObject())
  51. {
  52. return key;
  53. }
  54. if (_docRootjson.HasMember(langKey))
  55. {
  56. const rapidjson::Value& v = _docRootjson[langKey];
  57. if (v.HasMember(ckey))
  58. {
  59. return v[ckey].GetString();
  60. }
  61. }
  62. return key;
  63. }