123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- //
- // LocalizationMgr.cpp
- // redream_runtime
- //
- // Created by ZhengSong on 2022/7/11.
- //
- #include "LocalizationMgr.h"
- NS_CC_BEGIN
- static LocalizationMgr* _instance = nullptr;
- LocalizationMgr* LocalizationMgr::getInstance()
- {
- if(_instance == nullptr) {
- _instance = new LocalizationMgr();
- _instance->init();
- }
- return _instance;
- }
- bool LocalizationMgr::init()
- {
- _currentLanguageCode = Application::getInstance()->getCurrentLanguageFullCode();
- return true;
- }
- std::string LocalizationMgr::getString(const std::string& key, const std::string& path)
- {
- std::string ret = key;
- auto fullPath = FileUtils::getInstance()->fullPathForFilename(path);
- if(FileUtils::getInstance()->isFileExist(fullPath))
- {
- auto plistFile = _getFileFromCache(fullPath);
- auto iter = plistFile.find(key);
- if(iter != plistFile.end())
- {
- /*
- *从配置文件中根据contryCode寻找多语言,具体逻辑如下
- * 当前countryCode->细分语言找不到找主语->找英语->key
- */
- auto countryCode = getCurrentLanguageCode();
- auto dict = iter->second.asValueMap();
- if(dict.find(countryCode) != dict.end())
- {
- ret = dict[countryCode].asString();
- }
- else
- {
- std::string defaultCountryCode = "en";
- auto findDefaultCountryCode = [=](const std::string& code)->bool
- {
- if (dict.find(code) != dict.end())
- {
- return true;
- }
- return false;
- };
- if(countryCode.size() > 2) {
- //细分语言找不到找主语
- std::string shortCode = countryCode.substr(0, 2);
- if (dict.find(shortCode) != dict.end())
- {
- ret = dict[shortCode].asString();
- } else if(shortCode != defaultCountryCode){
- //如果当前语言找不到就找默认英文
- if(findDefaultCountryCode(defaultCountryCode))
- {
- ret = dict[defaultCountryCode].asString();
- }
- }
- } else if(countryCode != defaultCountryCode){
- //如果当前语言找不到就找默认语言
- if(findDefaultCountryCode(defaultCountryCode))
- {
- ret = dict[defaultCountryCode].asString();
- }
- }
- }
- }
- }
- return ret;
- }
- void LocalizationMgr::setCurrentLanguageCode(const std::string& code)
- {
- _currentLanguageCode = code;
- }
- std::string LocalizationMgr::getCurrentLanguageCode() const
- {
- return _currentLanguageCode;
- }
- const cocos2d::ValueMap LocalizationMgr::_getFileFromCache(const std::string& path)
- {
- auto iter = _plistMap.find(path);
- if(iter != _plistMap.end())
- {
- return iter->second;
- }
- _plistMap[path] = FileUtils::getInstance()->getValueMapFromFile(path);
- return _plistMap[path];
- }
- NS_CC_END
|