// // 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