/// <summary>
        /// Loads the parsed language file.(without the type identifiers)
        /// </summary>
        public static Dictionary <string, LocalizedObject> LoadParsedLanguageFile(string languageCode, bool isRoot)
        {
            string fileContents = string.Empty;
            string filePath     = null;

            if (isRoot)
            {
                filePath = LocalizationWorkspace.ResourcesFolderFilePath() + "/" +
                           LocalizationWorkspace.rootLanguageName + LocalizationWorkspace.txtFileEnding;
            }
            else
            {
                filePath = LocalizationWorkspace.ResourcesFolderFilePath() + "/" +
                           LocalizationWorkspace.rootLanguageName + "." + languageCode + LocalizationWorkspace.txtFileEnding;
            }

            if (!FileUtility.ReadFromFile(filePath, out fileContents))
            {
                Debug.LogError("Failed to read language from file - " + filePath);
            }


            var loadedLanguageDB = LanguageParser.LoadLanguage(fileContents);

            return(new Dictionary <string, LocalizedObject>(loadedLanguageDB));
        }
        /// <summary>
        /// Creates a new language
        /// </summary>
        /// <param name="languageName">The language code of the language to create</param>
        /// <param name="fromFile">Base language values to create a language from where each list of strings is a row.</param>
        public static void CreateNewLanguage(string languageName, List <List <string> > fromFile = null)
        {
            Dictionary <string, string> rootValues = LanguageHandlerEditor.LoadLanguageFile(null, true);

            //Copy the keys over to the new language
            Dictionary <string, string> baseDictionary = new Dictionary <string, string>();

            foreach (KeyValuePair <string, string> keyPair in rootValues)
            {
                baseDictionary.Add(keyPair.Key, "");
            }

            if (fromFile != null)
            {
                foreach (var row in fromFile)
                {
                    if (row.Count != 2)
                    {
                        Debug.LogError("The CSV file is not in the correct format.");
                        break;
                    }
                    baseDictionary[row[0]] = row[1];
                }
            }

            //Save the new language file
            SaveLanguageFile(baseDictionary, LocalizationWorkspace.LanguageFilePath(languageName));
        }
        /// <summary> Deletes the language. </summary>
        public static void DeleteLanguage(SmartCultureInfo cultureInfo)
        {
            string filePath = LocalizationWorkspace.LanguageFilePath(cultureInfo.languageCode);

            if (FileUtility.Exists(filePath))
            {
                FileUtility.Delete(filePath);
                FileUtility.Delete(filePath + LocalizationWorkspace.metaFileEnding);
            }
            //The text file
            filePath = LocalizationWorkspace.ResourcesFolderFilePath() + "/" + LocalizationWorkspace.rootLanguageName + "." + cultureInfo.languageCode + LocalizationWorkspace.txtFileEnding;
            if (FileUtility.Exists(filePath))
            {
                FileUtility.Delete(filePath);
                FileUtility.Delete(filePath + LocalizationWorkspace.metaFileEnding);
            }

            //The assets directory
            filePath = LocalizationWorkspace.LanguageRuntimeFolderPath(cultureInfo.languageCode);
            if (Directory.Exists(filePath))
            {
                Directory.Delete(filePath + "/", true);
                FileUtility.Delete(filePath + LocalizationWorkspace.metaFileEnding);
            }

            SmartCultureInfoCollection allCultures = SmartCultureInfoEx.Deserialize(LocalizationWorkspace.CultureInfoCollectionFilePath());

            LanguageHandlerEditor.CheckAndSaveAvailableLanguages(allCultures);
            AssetDatabase.Refresh();
        }
        /// <summary>
        /// Returns true if the window should show, returns false if not.
        /// If false, it will draw an editor label that says the window is unavailable
        /// </summary>
        public static bool ShouldShowWindow(bool isAvailableInPlayMode = false)
        {
            if (Application.isPlaying && !isAvailableInPlayMode)
            {
                GUILayout.Label("This Smart Localization Window is not available in play mode", EditorStyles.boldLabel);
                if (LanguageManager.HasInstance)
                {
                    if (GUILayout.Button("Go to translation window"))
                    {
                        TranslateLanguageWindow.ShowWindow(LanguageManager.Instance.GetCultureInfo(LanguageManager.Instance.CurrentlyLoadedCulture.languageCode), null);
                    }
                }
                return(false);
            }
            else if (!LocalizationWorkspace.Exists())
            {
                GUILayout.Label("There is no localization workspace available in this project", EditorStyles.boldLabel);
                if (GUILayout.Button("Create localization workspace"))
                {
                    if (LocalizationWorkspace.Create())
                    {
                        return(true);
                    }
                }

                return(false);
            }
            else
            {
                return(true);
            }
        }
	public static void UpdateLanguageFile(string languageCode, List<List<string>> values)
	{
		Dictionary<string,string> languageItems = null;
		if(FileUtility.Exists(LocalizationWorkspace.LanguageFilePath(languageCode)))
		{
			languageItems = LanguageHandlerEditor.LoadLanguageFile(languageCode, false);
		}
		else
		{
			languageItems = new Dictionary<string, string>();
		}
		
		int updatedKeys = 0;
		foreach (List<string> row in values)
		{
			if (row.Count != 2)
			{
				continue;
			}
			string key = row[0].TrimStart('\r', '\n').TrimEnd('\r', '\n').Trim();
			string value = row[1];

			if (!languageItems.ContainsKey(key))
			{
				continue;
			}

			languageItems[key] = value;
			updatedKeys++;
		}

		LanguageHandlerEditor.SaveLanguageFile(languageItems, LocalizationWorkspace.LanguageFilePath(languageCode));
		Debug.Log("Updated language:" + languageCode + ", Keys updated:" + updatedKeys);
	}
	/// <summary>
	/// Creates the initial root language file
	/// </summary>
	public static void CreateRootResourceFile()
	{
		//Add a dummy value so that the user will see how everything works
		Dictionary<string,string> baseDictionary = new Dictionary<string, string>();
		baseDictionary.Add("MyFirst.Key", "MyFirstValue");
		
		SaveLanguageFile(baseDictionary, LocalizationWorkspace.RootLanguageFilePath());
	}
 static void OnPostProcessScene()
 {
     if (LocalizationWorkspace.Exists() &&
         GenerateStorePresence &&
         !HasStorePresence)
     {
         GeneratePresence();
     }
 }
	/// <summary>
	/// Gets a SmartCultureInfoCollection with all the cultures not available in this workspace
	/// </summary>
	/// <param name="allCultures">The list of all the available cultures</param>
	/// <returns>A SmartCultureInfoCollection with all the cultures not available in this workspace</returns>
	public static SmartCultureInfoCollection GetNonAvailableLanguages(SmartCultureInfoCollection allCultures)
	{
		SmartCultureInfoCollection nonCreatedLanguages = new SmartCultureInfoCollection();
		
		foreach(SmartCultureInfo cultureInfo in allCultures.cultureInfos)
		{
			if(!FileUtility.Exists(LocalizationWorkspace.LanguageFilePath(cultureInfo.languageCode)))
			{
				nonCreatedLanguages.AddCultureInfo(cultureInfo);
			}
		}
		
		return nonCreatedLanguages;
	}
	/// <summary>
	/// Checks all the created languages and Saves the AvailableCultures xml.
	/// </summary>
	/// <param name="allCultures">A list of all the available cultures</param>
	/// <returns>A list of all the created languages</returns>
	public static SmartCultureInfoCollection CheckAndSaveAvailableLanguages(SmartCultureInfoCollection allCultures)
	{
		SmartCultureInfoCollection createdCultures = new SmartCultureInfoCollection();
		
		foreach(SmartCultureInfo cultureInfo in allCultures.cultureInfos)
		{
			if(FileUtility.Exists(LocalizationWorkspace.LanguageFilePath(cultureInfo.languageCode)))
			{
				createdCultures.AddCultureInfo(cultureInfo);
			}
		}

		createdCultures.Serialize(LocalizationWorkspace.AvailableCulturesFilePath());
		
		return createdCultures;
	}
        static bool CheckStorePresence()
        {
            string pluginDirectory   = "/" + PluginFolderName;
            string androidDirectory  = pluginDirectory + "/" + AndroidFolderName;
            string resourceDirectory = androidDirectory + "/" + ResourceFolderName;

            if (DirectoryUtility.ExistsRelative(pluginDirectory) &&
                DirectoryUtility.ExistsRelative(androidDirectory) &&
                DirectoryUtility.ExistsRelative(resourceDirectory) &&
                DirectoryUtility.ExistsRelative(resourceDirectory + "/" + ValuesFolderName) &&
                FileUtility.ExistsRelative(resourceDirectory + "/" + ValuesFolderName + "/" + StringsFileName))
            {
                if (!DoesFileHavePresence(Application.dataPath + "/" + resourceDirectory + "/" + ValuesFolderName + "/" + StringsFileName))
                {
                    return(false);
                }

                var availableCultures = SmartCultureInfoEx.Deserialize(LocalizationWorkspace.AvailableCulturesFilePath());

                foreach (SmartCultureInfo cultureInfo in availableCultures.cultureInfos)
                {
                    if (!IsLanguageSupported(cultureInfo.languageCode))
                    {
                        continue;
                    }

                    string currentLanguageFolderPath = GetValueFolderPath(resourceDirectory, cultureInfo);

                    if (!DirectoryUtility.ExistsRelative(currentLanguageFolderPath))
                    {
                        return(false);
                    }
                    if (!FileUtility.ExistsRelative(currentLanguageFolderPath + "/" + StringsFileName))
                    {
                        return(false);
                    }
                    else if (!DoesFileHavePresence(Application.dataPath + "/" + currentLanguageFolderPath + "/" + StringsFileName))
                    {
                        return(false);
                    }
                }

                return(true);
            }

            return(false);
        }
        void SaveRootLanguageFile()
        {
            var changeNewRootKeys   = new Dictionary <string, string>();
            var changeNewRootValues = new Dictionary <string, string>();

            for (int i = 0; i < changedRootKeys.Count; i++)
            {
                SerializableStringPair             rootKey   = changedRootKeys[i];
                SerializableLocalizationObjectPair rootValue = changedRootValues[i];
                //Check for possible duplicates and rename them
                string newKeyValue = LanguageDictionaryHelper.AddNewKeyPersistent(changeNewRootKeys,
                                                                                  rootKey.originalValue,
                                                                                  rootValue.changedValue.GetFullKey(rootKey.changedValue));

                //Check for possible duplicates and rename them(same as above)
                LanguageDictionaryHelper.AddNewKeyPersistent(changeNewRootValues, newKeyValue, rootValue.changedValue.TextValue);
            }

            //Add the full values before saving
            var changeNewRootKeysToSave   = new Dictionary <string, string>();
            var changeNewRootValuesToSave = new Dictionary <string, string>();

            foreach (var rootKey in changeNewRootKeys)
            {
                LocalizedObject thisLocalizedObject = parsedRootValues[rootKey.Key];
                changeNewRootKeysToSave.Add(thisLocalizedObject.GetFullKey(rootKey.Key), rootKey.Value);
                changeNewRootValuesToSave.Add(thisLocalizedObject.GetFullKey(rootKey.Key), changeNewRootValues[rootKey.Key]);
            }



            SmartCultureInfoCollection allCultures = SmartCultureInfoEx.Deserialize(LocalizationWorkspace.CultureInfoCollectionFilePath());

            LanguageHandlerEditor.SaveRootLanguageFile(changeNewRootKeysToSave, changeNewRootValuesToSave, LanguageHandlerEditor.CheckAndSaveAvailableLanguages(allCultures));

            //Fire the root language changed event
            if (OnRootFileChanged != null)
            {
                OnRootFileChanged();
            }

            //Reload the window(in case of duplicate keys)
            SetRootValues(LanguageHandlerEditor.LoadParsedLanguageFile(null, true));
        }
        /// <summary>Renames the localized file from resources.</summary>
        public static void RenameFileFromResources(string key, string newKey, SmartCultureInfo cultureInfo)
        {
            string languageFolderPath   = null;
            LocalizedObjectType keyType = LocalizedObject.GetLocalizedObjectType(key);
            string cleanKey             = LocalizedObject.GetCleanKey(key);
            string cleanNewKey          = LocalizedObject.GetCleanKey(newKey);

            switch (keyType)
            {
            case LocalizedObjectType.GAME_OBJECT:
                languageFolderPath = LocalizationWorkspace.LanguagePrefabsFolderPathRelative(cultureInfo.languageCode) + "/" + cleanKey + LocalizationWorkspace.prefabFileEnding;
                break;

            case LocalizedObjectType.AUDIO:
                languageFolderPath = LocalizationWorkspace.LanguageAudioFolderPathRelative(cultureInfo.languageCode);
                break;

            case LocalizedObjectType.TEXTURE:
                languageFolderPath = LocalizationWorkspace.LanguageTexturesFolderPathRelative(cultureInfo.languageCode);
                break;

            case LocalizedObjectType.TEXT_ASSET:
                languageFolderPath = LocalizationWorkspace.LanguageTextAssetsFolderPathRelative(cultureInfo.languageCode);
                break;

            case LocalizedObjectType.FONT:
                languageFolderPath = LocalizationWorkspace.LanguageFontsFolderPathRelative(cultureInfo.languageCode);
                break;
            }

            if (keyType != LocalizedObjectType.GAME_OBJECT)
            {
                string fileExtension = FileUtility.GetFileExtension(cleanKey, languageFolderPath);
                languageFolderPath += "/" + cleanKey + fileExtension;
            }

            if (FileUtility.Exists(Application.dataPath + languageFolderPath))
            {
                AssetDatabase.RenameAsset("Assets" + languageFolderPath, cleanNewKey);
            }

            AssetDatabase.Refresh();
        }
Exemple #13
0
        /// <summary>
        /// Checks .resx files and converts them into text assets that can be used at runtime
        /// </summary>
        public static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
        {
            //Only use this if there's a localization system created
            if (!LocalizationWorkspace.Exists())
            {
                return;
            }

            foreach (string asset in importedAssets)
            {
                if (asset.EndsWith(LocalizationWorkspace.resXFileEnding))
                {
                    string newFileName = LocalizationWorkspace.ResourcesFolderFilePath() + "/" + Path.GetFileNameWithoutExtension(asset) + LocalizationWorkspace.txtFileEnding;

                    if (!DirectoryUtility.CheckAndCreate(LocalizationWorkspace.ResourcesFolderFilePath()))
                    {
                        return;
                    }

                    //Delete the file if it already exists
                    if (FileUtility.Exists(newFileName))
                    {
                        FileUtility.Delete(newFileName);
                    }

                    string fileData = "";
                    using (StreamReader reader = new StreamReader(asset))
                    {
                        fileData = reader.ReadToEnd();
                    }


                    FileUtility.WriteToFile(newFileName, fileData);

                    SmartCultureInfoCollection allCultures = SmartCultureInfoEx.Deserialize(LocalizationWorkspace.CultureInfoCollectionFilePath());
                    LanguageHandlerEditor.CheckAndSaveAvailableLanguages(allCultures);

                    AssetDatabase.Refresh(ImportAssetOptions.Default);
                }
            }
        }
        /// <summary> Deletes the localized file from resources.</summary>
        public static void DeleteFileFromResources(string key, SmartCultureInfo cultureInfo)
        {
            string languageFolderPath   = string.Empty;
            string cleanKey             = LocalizedObject.GetCleanKey(key);
            LocalizedObjectType keyType = LocalizedObject.GetLocalizedObjectType(key);

            switch (keyType)
            {
            case LocalizedObjectType.GameObject:
                languageFolderPath = LocalizationWorkspace.LanguagePrefabsFolderPathRelative(cultureInfo.languageCode) + "/" + cleanKey + LocalizationWorkspace.prefabFileEnding;
                break;

            case LocalizedObjectType.Audio:
                languageFolderPath = LocalizationWorkspace.LanguageAudioFolderPathRelative(cultureInfo.languageCode);
                break;

            case LocalizedObjectType.Texture:
                languageFolderPath = LocalizationWorkspace.LanguageTexturesFolderPathRelative(cultureInfo.languageCode);
                break;

            case LocalizedObjectType.TextAsset:
                languageFolderPath = LocalizationWorkspace.LanguageTextAssetsFolderPathRelative(cultureInfo.languageCode);
                break;

            case LocalizedObjectType.Font:
                languageFolderPath = LocalizationWorkspace.LanguageFontsFolderPathRelative(cultureInfo.languageCode);
                break;
            }

            if (keyType != LocalizedObjectType.GameObject)
            {
                string fileExtension = FileUtility.GetFileExtension(cleanKey, languageFolderPath);
                languageFolderPath += "/" + cleanKey + fileExtension;
            }

            if (FileUtility.Exists(Application.dataPath + languageFolderPath))
            {
                AssetDatabase.DeleteAsset("Assets" + languageFolderPath);
            }
            AssetDatabase.Refresh();
        }
        /// <summary>
        /// Returns if the key selector should be shown.
        /// </summary>
        /// <returns>Returns if the key selector should be shown.</returns>
        public static bool ShouldShowKeySelector()
        {
            if (Application.isPlaying)
            {
                GUILayout.Label("Feature not available in play mode.", EditorStyles.miniLabel);
                return(false);
            }

            if (!LocalizationWorkspace.Exists())
            {
                GUILayout.Label("There is no Smart Localization workspace created", EditorStyles.miniLabel);
                //There is no language created
                if (GUILayout.Button("Create Workspace"))
                {
                    LocalizationWorkspace.Create();
                }
                return(false);
            }

            return(true);
        }
Exemple #16
0
        void Initialize()
        {
            if (undoManager == null)
            {
                undoManager = new HOEditorUndoManager(this, "SmartLocalization-Main");
            }

            if (availableCultures == null)
            {
                allCultures = SmartCultureInfoEx.Deserialize(LocalizationWorkspace.CultureInfoCollectionFilePath());

                if (allCultures.version != SmartCultureInfoCollection.LatestVersion)
                {
                    LocalizationWorkspace.GenerateCultureInfoCollection(allCultures);
                    allCultures = SmartCultureInfoEx.Deserialize(LocalizationWorkspace.CultureInfoCollectionFilePath());
                }
                InitializeCultureCollections();
            }

            if (EditorPrefs.HasKey(MicrosoftTranslatorIDSaveKey) && EditorPrefs.HasKey(MicrosoftTranslatorSecretSaveKey) && EditorPrefs.HasKey(KeepAuthenticatedSaveKey))
            {
                mtClientID     = EditorPrefs.GetString(MicrosoftTranslatorIDSaveKey);
                mtClientSecret = EditorPrefs.GetString(MicrosoftTranslatorSecretSaveKey);
                keepTranslatorAuthenticated = EditorPrefs.GetBool(KeepAuthenticatedSaveKey);
            }

            InitializeTranslator();

            generateAndroidPresence = AndroidStorePresenceGenerator.GenerateStorePresence;
            generateiOSPresence     = IOSStorePresenceGenerator.GenerateStorePresence;

            settingsList.Clear();
            settingsList.Add("SETTINGS");
            settingsList.Add("STOREPRESENCE");
            settingsList.Add("AUTOTRANSLATE");

            isInitialized = true;

            GUIUtility.keyboardControl = 0;
        }
        private void SaveAndRebuild()
        {
            //Copy everything into a dictionary
            Dictionary <string, string> newLanguageValues = new Dictionary <string, string>();

            foreach (var objectPair in loadedLanguageValues)
            {
                if (objectPair.changedValue.ObjectType == LocalizedObjectType.STRING)
                {
                    newLanguageValues.Add(objectPair.changedValue.GetFullKey(objectPair.keyValue), objectPair.changedValue.TextValue);
                }
                else
                {
                    //Delete the file in case there was a file there previously
                    LanguageHandlerEditor.DeleteFileFromResources(objectPair.changedValue.GetFullKey(objectPair.keyValue), currentCultureInfo);

                    //Store the path to the file
                    string pathValue = string.Empty;
                    if (objectPair.changedValue.OverrideLocalizedObject)
                    {
                        pathValue = "override=" + objectPair.changedValue.OverrideObjectLanguageCode;
                    }
                    else
                    {
                        pathValue = LanguageHandlerEditor.CopyFileIntoResources(objectPair, currentCultureInfo);
                    }
                    newLanguageValues.Add(objectPair.changedValue.GetFullKey(objectPair.keyValue), pathValue);
                }
            }
            LanguageHandlerEditor.SaveLanguageFile(newLanguageValues, LocalizationWorkspace.LanguageFilePath(currentCultureInfo.languageCode));
            guiChanged = false;
            GUIUtility.keyboardControl = 0;

            if (Application.isPlaying && LanguageManager.HasInstance)
            {
                LanguageManager.Instance.ChangeLanguage(currentCultureInfo.languageCode);
            }
        }
Exemple #18
0
	/// <summary> Copies the file into the resources folder. Naming the new asset to KEY </summary>
	public static string CopyFileIntoResources(SerializableLocalizationObjectPair objectPair, SmartCultureInfo thisCultureInfo)
	{
		if(!DirectoryUtility.CheckAndCreate(LocalizationWorkspace.LanguageRuntimeFolderPath(thisCultureInfo.languageCode)))
		{
			return "";
		}


		string newFileName = objectPair.keyValue;
		string filePath = string.Empty;
		string currentAssetPath = string.Empty;
		LocalizedObject objectToCopy = objectPair.changedValue;

		if(objectToCopy.ObjectType == LocalizedObjectType.AUDIO && objectToCopy.ThisAudioClip != null)
		{
			filePath = LocalizationWorkspace.LanguageAudioFolderPath(thisCultureInfo.languageCode);
			currentAssetPath = AssetDatabase.GetAssetPath(objectToCopy.ThisAudioClip);
		}
		else if(objectToCopy.ObjectType == LocalizedObjectType.TEXTURE && objectToCopy.ThisTexture != null)
		{
			filePath = LocalizationWorkspace.LanguageTexturesFolderPath(thisCultureInfo.languageCode);
			currentAssetPath = AssetDatabase.GetAssetPath(objectToCopy.ThisTexture);
		}
		else if(objectToCopy.ObjectType == LocalizedObjectType.GAME_OBJECT && objectToCopy.ThisGameObject != null)
		{
			filePath = LocalizationWorkspace.LanguagePrefabsFolderPath(thisCultureInfo.languageCode);
			currentAssetPath = AssetDatabase.GetAssetPath(objectToCopy.ThisGameObject);
		}
		else if(objectToCopy.ObjectType == LocalizedObjectType.TEXT_ASSET && objectToCopy.ThisTextAsset != null)
		{
			filePath = LocalizationWorkspace.LanguageTextAssetsFolderPath(thisCultureInfo.languageCode);
			currentAssetPath = AssetDatabase.GetAssetPath(objectToCopy.ThisTextAsset);
		}
		else if(objectToCopy.ObjectType == LocalizedObjectType.FONT && objectToCopy.Font != null)
		{
			filePath = LocalizationWorkspace.LanguageFontsFolderPath(thisCultureInfo.languageCode);
			currentAssetPath = AssetDatabase.GetAssetPath(objectToCopy.Font);
		}
		else
		{
			return string.Empty;
		}

		if(!DirectoryUtility.CheckAndCreate(filePath))
		{
			return "";
		}

		//Get the fileExtension of the asset
		string fileExtension = FileUtility.GetFileExtension(Application.dataPath + currentAssetPath);
		
		if(objectToCopy.ObjectType != LocalizedObjectType.GAME_OBJECT){
	
			//Copy or replace the file to the new path
			FileUtil.ReplaceFile(currentAssetPath, filePath + "/" + newFileName + fileExtension);
	
			string metaFile = Application.dataPath.Substring(0, Application.dataPath.Length - "Assets".Length) + 
								currentAssetPath.Substring(0, currentAssetPath.Length - fileExtension.Length) + fileExtension + ".meta";
			if(File.Exists(metaFile))
			{
				FileUtil.ReplaceFile(metaFile, filePath + "/" + newFileName + fileExtension + ".meta");
			}
		}
		else{
			string relativePath = filePath + "/" + newFileName + fileExtension;
			relativePath = "Assets" + relativePath.Substring(Application.dataPath.Length);
			PrefabUtility.CreatePrefab(relativePath, objectToCopy.ThisGameObject);
		}

		return AssetDatabase.AssetPathToGUID(currentAssetPath);
	}
Exemple #19
0
	/// <summary>
	/// Loads all the language files with their raw values
	/// </summary>
	/// <returns>A dictionary with all the language dictionaries. The language codes are being used as keys</returns>
	public static Dictionary<string,Dictionary<string,string>> LoadAllLanguageFiles()
	{
		var allLanguages = new Dictionary<string,Dictionary<string,string>>();
		var availableCultures = LanguageHandlerEditor.CheckAndSaveAvailableLanguages(SmartCultureInfoEx.Deserialize(LocalizationWorkspace.CultureInfoCollectionFilePath()));

		foreach(SmartCultureInfo info in availableCultures.cultureInfos)
		{
			allLanguages.Add(info.languageCode, LoadLanguageFile(info.languageCode, false));
		}

		return allLanguages;
	}
Exemple #20
0
	/// <summary>
	/// Saves the root language file and updates all the available languages.
	/// </summary>
	public static void SaveRootLanguageFile(Dictionary<string,string> changedRootKeys, Dictionary<string,string> changedRootValues, SmartCultureInfoCollection availableCultures)
	{
		//The dictionary with all the final changes
		Dictionary<string,string> changedDictionary = new Dictionary<string, string>();
		
		foreach(KeyValuePair<string,string> changedKey in changedRootKeys)
		{
			if(changedKey.Key == changedKey.Value)
			{
				//The key is not changed, just add the key and the changed value to the new dictionary
				LanguageDictionaryHelper.AddNewKeyPersistent(changedDictionary, changedKey.Key, changedRootValues[changedKey.Key]);
			}
			else
			{
				//Add the new key along with the new changed value
				LanguageDictionaryHelper.AddNewKeyPersistent(changedDictionary, changedKey.Value, changedRootValues[changedKey.Key]);
			}
		}
		
		//Look if any keys were deleted,(so that we can delete the created files)
		List<string> deletedKeys = new List<string>();
		IEnumerable<string> originalKeys = LoadLanguageFile(null, true).Keys;
		foreach(string originalKey in originalKeys)
		{
			bool foundMatch = false;
			foreach(KeyValuePair<string,string> changedKey in changedRootKeys)
			{
				if(originalKey == changedKey.Key)
				{
					foundMatch = true;
					break;
				}
			}
			if(!foundMatch)
			{
				deletedKeys.Add(originalKey);
			}
		}
		
		//Save the language file
		SaveLanguageFile(changedDictionary, LocalizationWorkspace.RootLanguageFilePath());
		
		//Change all the key values for all the translated languages
		var changedCultureValues = new Dictionary<string, string>();
		foreach(var cultureInfo in availableCultures.cultureInfos)
		{
			var currentCultureValues = LoadLanguageFile(cultureInfo.languageCode, false);
			foreach(var changedKey in changedRootKeys)
			{
				string currentValue;
				currentCultureValues.TryGetValue(changedKey.Key, out currentValue);
				if(currentValue == null)
				{
					currentValue = "";
				}
				
				//If the key is changed, we need to change the asset names as well
				if(changedKey.Key != changedKey.Value && currentValue != "")
				{
					LocalizedObjectType originalType = LocalizedObject.GetLocalizedObjectType(changedKey.Key);
					LocalizedObjectType changedType = LocalizedObject.GetLocalizedObjectType(changedKey.Value);
					
					if(originalType != changedType)
					{
						//If the type is changed, then delete the asset and reset the value
						DeleteFileFromResources(changedKey.Key, cultureInfo);
						currentValue = "";
					}
					else
					{
						//just rename it otherwise
						RenameFileFromResources(changedKey.Key, changedKey.Value, cultureInfo);
					}
				}
				
				LanguageDictionaryHelper.AddNewKeyPersistent(changedCultureValues, changedKey.Value, currentValue);
			}
			
			//Save the language file
			SaveLanguageFile (changedCultureValues, LocalizationWorkspace.LanguageFilePath(cultureInfo.languageCode));
			changedCultureValues.Clear();
			
			//Remove all the deleted files associated with the deleted keys
			foreach(string deletedKey in deletedKeys)
			{
				Debug.Log("Deleted key!:" + deletedKey);
				DeleteFileFromResources(deletedKey, cultureInfo);
			}
		}
	}
Exemple #21
0
        void OnGUI()
        {
            if (LocalizationWindowUtility.ShouldShowWindow())
            {
                GUILayout.Label("Create a new culture info", EditorStyles.boldLabel);

                languageCode = EditorGUILayout.TextField("Language Code", languageCode);
                if (languageCode != null)
                {
                    languageCode = languageCode.RemoveWhitespace();
                }

                englishName   = EditorGUILayout.TextField("English Name", englishName);
                nativeName    = EditorGUILayout.TextField("Native Name", nativeName);
                isRightToLeft = EditorGUILayout.Toggle("Is Right To Left", isRightToLeft);

                if (GUILayout.Button("Create"))
                {
                    SmartCultureInfo newInfo = new SmartCultureInfo();
                    newInfo.languageCode  = languageCode;
                    newInfo.englishName   = englishName.Trim();
                    newInfo.nativeName    = nativeName.Trim();
                    newInfo.isRightToLeft = isRightToLeft;

                    SmartCultureInfoCollection allCultures = SmartCultureInfoEx.Deserialize(LocalizationWorkspace.CultureInfoCollectionFilePath());
                    if (!allCultures.IsCultureInCollection(newInfo))
                    {
                        allCultures.AddCultureInfo(newInfo);
                        allCultures.Serialize(LocalizationWorkspace.CultureInfoCollectionFilePath());
                        LanguageHandlerEditor.CheckAndSaveAvailableLanguages(allCultures);

                        showHelpMessage = true;
                        helpMessageType = MessageType.Info;
                        helpMessage     = string.Format("Successfully created language!\n Language Code: {0}\n English Name:{1}\n Native Name:{2}\n IsRightToLeft:{3}",
                                                        newInfo.languageCode, newInfo.englishName, newInfo.nativeName, newInfo.isRightToLeft);

                        if (parentWindow != null)
                        {
                            parentWindow.InitializeCultureCollections(true);
                        }

                        this.Close();
                    }
                    else
                    {
                        SmartCultureInfo conflictingCulture  = allCultures.FindCulture(newInfo);
                        string           conflictingVariable = null;

                        if (conflictingCulture.languageCode.ToLower() == newInfo.languageCode.ToLower())
                        {
                            conflictingVariable = "Language Code:" + newInfo.languageCode;
                        }
                        else if (conflictingCulture.englishName.ToLower() == newInfo.englishName.ToLower())
                        {
                            conflictingVariable = "English Name:" + newInfo.englishName;
                        }

                        showHelpMessage = true;
                        helpMessageType = MessageType.Error;
                        helpMessage     = string.Format("Failed to create language!\n Conflicting variable - {0}\n\n",
                                                        conflictingVariable);

                        helpMessage += string.Format("Conflicting Culture \n Language Code: {0}\n English Name:{1}\n Native Name:{2}",
                                                     conflictingCulture.languageCode, conflictingCulture.englishName, conflictingCulture.nativeName);
                    }
                }

                if (showHelpMessage)
                {
                    EditorGUILayout.HelpBox(helpMessage, helpMessageType);
                }
            }
        }
        /// <summary>
        /// Generates all the files for store presence
        /// </summary>
        /// <returns>If the operation was successful</returns>
        public static bool GeneratePresence()
        {
            if (HasStorePresence)
            {
                return(true);
            }

            string currentDirectory = Application.dataPath + "/" + PluginFolderName;

            if (!DirectoryUtility.CheckAndCreate(currentDirectory))
            {
                return(false);
            }

            currentDirectory += "/" + AndroidFolderName;
            if (!DirectoryUtility.CheckAndCreate(currentDirectory))
            {
                return(false);
            }

            currentDirectory += "/" + ResourceFolderName;
            if (!DirectoryUtility.CheckAndCreate(currentDirectory))
            {
                return(false);
            }

            //Create the default directory
            if (!DirectoryUtility.CheckAndCreate(currentDirectory + "/" + ValuesFolderName))
            {
                return(false);
            }

            if (!AppendOrCreateStringsFile(currentDirectory + "/" + ValuesFolderName + "/" + StringsFileName))
            {
                return(false);
            }

            var availableCultures = SmartCultureInfoEx.Deserialize(LocalizationWorkspace.AvailableCulturesFilePath());

            foreach (SmartCultureInfo cultureInfo in availableCultures.cultureInfos)
            {
                if (!IsLanguageSupported(cultureInfo.languageCode))
                {
                    continue;
                }

                string currentLanguageFolderPath = GetValueFolderPath(currentDirectory, cultureInfo);

                if (!DirectoryUtility.CheckAndCreate(currentLanguageFolderPath))
                {
                    return(false);
                }

                if (!AppendOrCreateStringsFile(currentLanguageFolderPath + "/" + StringsFileName))
                {
                    return(false);
                }
            }

            AssetDatabase.Refresh();

            return(true);
        }
        public void Initialize(SmartCultureInfo thisCultureInfo, bool forceNewLanguage = false)
        {
            if (thisCultureInfo != null)
            {
                if (undoManager == null)
                {
                    // Instantiate Undo Manager
                    undoManager = new HOEditorUndoManager(this, "Smart Localization - Translate Language Window");
                }

                if (thisCultureInfo != null)
                {
                    bool newLanguage = thisCultureInfo != this.currentCultureInfo ? true : false;

                    if (Application.isPlaying || forceNewLanguage)
                    {
                        newLanguage = true;
                    }

                    this.currentCultureInfo = thisCultureInfo;
                    if (loadedLanguageValues == null || loadedLanguageValues.Count < 1 || newLanguage)
                    {
                        InitializeLanguage(thisCultureInfo,
                                           LanguageHandlerEditor.LoadParsedLanguageFile(null, true),
                                           LanguageHandlerEditor.LoadParsedLanguageFile(thisCultureInfo.languageCode,
                                                                                        false));
                    }
                }

                settingsList.Clear();
                settingsList.Add("SETTINGS");
                settingsList.Add("CONVERTLINEBREAK");
                settingsList.Add("WATCHFILE");
                settingsList.Add("AUTOTRANSLATE");
                settingsList.Add("GENERAL");

#if UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3
                if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.WebPlayer &&
                    EditorUserBuildSettings.activeBuildTarget != BuildTarget.WebPlayerStreamed)
#endif
                {
                    settingsList.Add("SORT");
                }

                settingsList.Add("SEARCH");

                settingsAdaptor     = new SettingsListAdaptor(settingsList, DrawSettingsItem, 20);
                settingsContextMenu = new SettingsMenuControl();

                listColumns = new EditorColumns(0.02f, true);
                listColumns.AddColumn("Copy", 0.1f);
                listColumns.AddColumn("Translate", 0.1f);
                listColumns.AddColumn("Key", 0.21f);
                listColumns.AddColumn("Comment", 0.21f);
                listColumns.AddColumn("Override", 0.07f);
                listColumns.AddColumn("Value", 0.25f);
                listColumns.RecalculateColumnWidths();

                if (EditorPrefs.HasKey(CollapseMultilineSaveKey))
                {
                    collapseMultilineFields = EditorPrefs.GetBool(CollapseMultilineSaveKey);
                }

                GUIUtility.keyboardControl = 0;

                SmartCultureInfoCollection allCultures       = SmartCultureInfoEx.Deserialize(LocalizationWorkspace.CultureInfoCollectionFilePath());
                SmartCultureInfoCollection availableCultures = LanguageHandlerEditor.CheckAndSaveAvailableLanguages(allCultures);
                otherAvailableLanguageCodes.Clear();
                otherAvailableLanguageCodesArray = null;
                foreach (SmartCultureInfo otherCulture in availableCultures.cultureInfos)
                {
                    if (otherCulture.languageCode != thisCultureInfo.languageCode)
                    {
                        otherAvailableLanguageCodes.Add(otherCulture.languageCode);
                    }
                }

                if (otherAvailableLanguageCodes.Count > 0)
                {
                    otherAvailableLanguageCodesArray = otherAvailableLanguageCodes.ToArray();
                }
            }
        }
        void OnGotAvailableLanguages(bool success, List <string> availableLanguages)
        {
            if (!success)
            {
                return;
            }

            availableTranslateFromLanguages.Clear();
            //Clear the array
            if (availableTranslateLangEnglishNames != null)
            {
                Array.Clear(availableTranslateLangEnglishNames, 0, availableTranslateLangEnglishNames.Length);
                availableTranslateLangEnglishNames = null;
            }

            if (translateFromDictionary != null)
            {
                translateFromDictionary.Clear();
                translateFromDictionary = null;
            }
            translateFromLanguageValue    = 0;
            oldTranslateFromLanguageValue = 0;

            List <string> englishNames = new List <string>();

            englishNames.Add("None");
            if (availableLanguages.Contains(currentCultureInfo.languageCode))
            {
                canLanguageBeTranslated = true;

                SmartCultureInfoCollection allCultures       = SmartCultureInfoEx.Deserialize(LocalizationWorkspace.CultureInfoCollectionFilePath());
                SmartCultureInfoCollection availableCultures = LanguageHandlerEditor.CheckAndSaveAvailableLanguages(allCultures);

                foreach (SmartCultureInfo cultureInfo in availableCultures.cultureInfos)
                {
                    if (cultureInfo.languageCode != currentCultureInfo.languageCode && availableLanguages.Contains(cultureInfo.languageCode))
                    {
                        availableTranslateFromLanguages.Add(cultureInfo);
                        englishNames.Add(cultureInfo.englishName);
                    }
                }
            }
            else
            {
                canLanguageBeTranslated = false;
            }
            availableTranslateLangEnglishNames = englishNames.ToArray();
        }
        public static void OnPostProcessBuild(BuildTarget target, string path)
        {
#if UNITY_4_6 || UNITY_4_7
            if (target != BuildTarget.iPhone)
#else
            if (target != BuildTarget.iOS)
#endif
            {
                return;
            }

            if (!GenerateStorePresence)
            {
                return;
            }

            const string fileName = "Info.plist";
            string       fullPath = Path.Combine(path, fileName);

            var doc = new XmlDocument();
            doc.Load(fullPath);

            var dict = FindPlistDictNode(doc);
            if (dict == null)
            {
                Debug.LogError("[Smartlocalization] Error parsing " + fullPath);
                return;
            }

            AddChildElement(doc, dict, "key", "CFBundleLocalizations");
            var arrayKey = AddChildElement(doc, dict, "array");

            var availableCultures = SmartCultureInfoEx.Deserialize(LocalizationWorkspace.AvailableCulturesFilePath());

            foreach (var cultureInfo in availableCultures.cultureInfos)
            {
                AddChildElement(doc, arrayKey, "string", cultureInfo.languageCode);
            }

            doc.Save(fullPath);

            //the xml writer barfs writing out part of the plist header.
            //so we replace the part that it wrote incorrectly here
            string textPlist = null;
            using (var reader = new StreamReader(fullPath))
            {
                textPlist = reader.ReadToEnd();
            }

            int fixupStart = textPlist.IndexOf("<!DOCTYPE plist PUBLIC", System.StringComparison.Ordinal);
            if (fixupStart <= 0)
            {
                return;
            }
            int fixupEnd = textPlist.IndexOf('>', fixupStart);
            if (fixupEnd <= 0)
            {
                return;
            }

            string fixedPlist = textPlist.Substring(0, fixupStart);
            fixedPlist += "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">";
            fixedPlist += textPlist.Substring(fixupEnd + 1);

            using (var writer = new StreamWriter(fullPath, false))
            {
                writer.Write(fixedPlist);
            }
        }