Ejemplo n.º 1
0
        /// <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();
        }
Ejemplo n.º 2
0
        /// <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("Файл CSV не в правильном формате.");
                        break;
                    }
                    baseDictionary[row[0]] = row[1];
                }
            }

            //Save the new language file
            SaveLanguageFile(baseDictionary, LocalizationWorkspace.LanguageFilePath(languageName));
        }
Ejemplo n.º 3
0
        /// <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("Не удалось прочитать язык из файла - " + filePath);
            }


            var loadedLanguageDB = LanguageParser.LoadLanguage(fileContents);

            return(new Dictionary <string, LocalizedObject>(loadedLanguageDB));
        }
Ejemplo n.º 4
0
        public void InitializeCultureCollections(bool reloadAllCultures = false)
        {
            if (reloadAllCultures)
            {
                allCultures = SmartCultureInfoEx.Deserialize(LocalizationWorkspace.CultureInfoCollectionFilePath());
            }

            availableCultures    = LanguageHandlerEditor.CheckAndSaveAvailableLanguages(allCultures);
            nonAvailableCultures = LanguageHandlerEditor.GetNonAvailableLanguages(allCultures);

            availableCultures.cultureInfos.Sort((a, b) =>
            {
                return(a.englishName.CompareTo(b.englishName));
            });
            nonAvailableCultures.cultureInfos.Sort((a, b) =>
            {
                return(a.englishName.CompareTo(b.englishName));
            });

            availableCultures.cultureInfos.Insert(0, new SmartCultureInfo(string.Empty, "ROOT", "ROOT", false));

            languageListAdaptor     = new SmartCultureInfoListAdaptor(availableCultures.cultureInfos, DrawAvailableLanguageItem, 28);
            languageListContextMenu = new SmartCultureInfoMenuControl();

            createListAdaptor     = new CreateLanguageListAdaptor(nonAvailableCultures.cultureInfos, DrawCreateLanguageItem, 15);
            createListContextMenu = new CreateLanguageMenuControl();

            settingsAdaptor     = new SettingsListAdaptor(settingsList, DrawSettingsItem, 110);
            settingsContextMenu = new SettingsMenuControl();
        }
Ejemplo n.º 5
0
        /// <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());
        }
Ejemplo n.º 6
0
        /// <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);
        }
Ejemplo n.º 7
0
        /// <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);
        }
Ejemplo n.º 8
0
        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));
        }
Ejemplo n.º 9
0
        /// <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();
        }
Ejemplo n.º 10
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);
                }
            }
        }
Ejemplo n.º 11
0
        /// <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("Функция недоступна в режиме воспроизведения.", EditorStyles.miniLabel);
                return(false);
            }

            if (!LocalizationWorkspace.Exists())
            {
                GUILayout.Label("Не создано рабочее пространство Smart Localization", EditorStyles.miniLabel);
                //There is no language created
                if (GUILayout.Button("Создать рабочую область"))
                {
                    LocalizationWorkspace.Create();
                }
                return(false);
            }

            return(true);
        }
Ejemplo n.º 12
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);
            }
        }
Ejemplo n.º 13
0
        void Initialize()
        {
            if (undoManager == null)
            {
                undoManager = new HOEditorUndoManager(this, "GGLocalization-Main");          //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();

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

            isInitialized = true;

            GUIUtility.keyboardControl = 0;
        }
Ejemplo n.º 14
0
        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("Обновленный язык:" + languageCode + ", Ключ обновлен:" + updatedKeys);
        }
Ejemplo n.º 15
0
        void OnGUI()
        {
            if (LocalizationWindowUtility.ShouldShowWindow())
            {
                GUILayout.Label("Создать новую информацию о культуре", EditorStyles.boldLabel);

                languageCode = EditorGUILayout.TextField("Код языка", languageCode);
                if (languageCode != null)
                {
                    languageCode = languageCode.RemoveWhitespace();
                }

                englishName   = EditorGUILayout.TextField("Английское имя", englishName);
                nativeName    = EditorGUILayout.TextField("Родное имя", nativeName);
                isRightToLeft = EditorGUILayout.Toggle("Справа налево", isRightToLeft);

                if (GUILayout.Button("Создать"))
                {
                    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("Язык успешно создан!\n Код языка: {0}\n Английское имя:{1}\n Родное имя:{2}\n Справа налево:{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("Не удалось создать язык!\n Конфликтующая переменная - {0}\n\n",
                                                        conflictingVariable);

                        helpMessage += string.Format("Конфликтующая культура \n Код языка: {0}\n Английское имя:{1}\n Родное имя:{2}",
                                                     conflictingCulture.languageCode, conflictingCulture.englishName, conflictingCulture.nativeName);
                    }
                }

                if (showHelpMessage)
                {
                    EditorGUILayout.HelpBox(helpMessage, helpMessageType);
                }
            }
        }
Ejemplo n.º 16
0
        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();
        }
Ejemplo n.º 17
0
        public void Initialize(SmartCultureInfo thisCultureInfo, bool forceNewLanguage = false)
        {
            if (thisCultureInfo != null)
            {
                if (undoManager == null)
                {
                    // Instantiate Undo Manager
                    undoManager = new HOEditorUndoManager(this, "GGLocalization - Translate Language Window");              //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("Копия", 0.1f);           // Copy
                listColumns.AddColumn("Перевод", 0.1f);         // Translate
                listColumns.AddColumn("Ключ", 0.21f);           // Key
                listColumns.AddColumn("Комментарий", 0.21f);    // Comment
                listColumns.AddColumn("Переопределить", 0.07f); //Override
                listColumns.AddColumn("Значение", 0.25f);       // Value
                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();
                }
            }
        }
Ejemplo n.º 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);
                //1PrefabUtility.CreatePrefab(relativePath, objectToCopy.ThisGameObject);
                PrefabUtility.SaveAsPrefabAsset(objectToCopy.ThisGameObject, relativePath);             // TODO Перепроверить
            }

            return(AssetDatabase.AssetPathToGUID(currentAssetPath));
        }
Ejemplo n.º 19
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("Ключ удален!:" + deletedKey);
                    DeleteFileFromResources(deletedKey, cultureInfo);
                }
            }
        }
Ejemplo n.º 20
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);
        }