string GetLocalizedString(StringTable table, string entryName)
        {
            // Get the table entry. The entry contains the localized string and Metadata
            var entry = table.GetEntry(entryName);

            return(entry.GetLocalizedString()); // We can pass in optional arguments for Smart Format or String.Format here
        }
        public override void ReadRow(SharedTableData.SharedTableEntry keyEntry, CsvReader reader)
        {
            if (m_ImportTable == null)
            {
                return;
            }

            // Get the entry or create one
            StringTableEntry entry = m_ImportTable.GetEntry(keyEntry.Id) ?? m_ImportTable.AddEntry(keyEntry.Id, string.Empty);

            // Get the metadata or add one
            var metadata = entry.GetMetadata <MyCustomDataMetadata>();

            if (metadata == null)
            {
                metadata = new MyCustomDataMetadata();
                entry.AddMetadata(metadata);
            }

            if (m_SomeValueIndex != -1)
            {
                metadata.someValue = reader.GetField(m_SomeValueIndex);
            }

            if (m_SomeOtherValueIndex != -1)
            {
                metadata.someOtherValue = reader.GetField <int>(m_SomeOtherValueIndex);
            }
        }
Esempio n. 3
0
 public string GetLocalizedString(string id, params object[] args)
 {
     if (!m_translations)
     {
         return(string.Format(id, args));
     }
     return(m_translations.GetEntry(id).GetLocalizedString(args));
 }
    static string GetLocalizedString(StringTable table, string entryName)
    {
        var entry = table.GetEntry(entryName);

        // We can also extract Metadata here
        var comment = entry.GetMetadata <Comment>();

        if (comment != null)
        {
            Debug.Log($"Found metadata comment for {entryName} - {comment.CommentText}");
        }

        return(entry.GetLocalizedString()); // We can pass in optional arguments for Smart Format or String.Format here.
    }
Esempio n. 5
0
        /// <summary>
        /// Attempts to read a localized string from a named table collection.
        /// </summary>
        /// <param name="collection">Name of table collection.</param>
        /// <param name="id">ID of string to get.</param>
        /// <param name="result">Localized string result or null/empty.</param>
        /// <returns>True if string found, otherwise false.</returns>
        public virtual bool GetLocalizedString(string collection, string id, out string result)
        {
            result = string.Empty;
            if (string.IsNullOrEmpty(collection))
            {
                if (localizedStringDebug)
                {
                    Debug.Log("Collection name is null or empty.");
                }
                return(false);
            }

            StringTable table = null;
            var         sd    = LocalizationSettings.StringDatabase;
            var         op    = sd.GetTableAsync(collection);

            op.WaitForCompletion();
            if (op.IsDone)
            {
                table = op.Result;
            }
            else
            {
                Debug.LogErrorFormat("GetLocalizedString() failed on collection='{0}' id='{1}'", collection, id);
            }

            if (table != null)
            {
                var entry = table.GetEntry(id);
                if (entry != null)
                {
                    result = entry.GetLocalizedString();
                    if (localizedStringDebug)
                    {
                        Debug.LogFormat("Found localized string for locale {0}\n{1}", LocalizationSettings.SelectedLocale.name, result);
                    }
                    return(true);
                }
            }
            else
            {
                if (localizedStringDebug)
                {
                    Debug.LogFormat("StringTable collection '{0}' not found", collection);
                }
            }

            return(false);
        }
Esempio n. 6
0
        static void SplitQuestionnaireRecord(string text, string key, StringTable targetTable, bool overwriteExistingKeys, ref int copiedNew, ref int copiedOverwrite)
        {
            string[] splitText = text.Split('{');

            if (splitText == null || splitText.Length == 0)
            {
                Debug.LogErrorFormat("SplitQuestionnaireRecord() found 0 entries.", key);
                return;
            }

            for (int i = 0; i < splitText.Length; i++)
            {
                string itemKey  = string.Format("{0}.{1}", key, i);
                string itemText = splitText[i];

                // Discard any empty records and trailing markup end record
                if (string.IsNullOrEmpty(itemText) || string.Compare(markupEndRecord, itemText) == 0)
                {
                    continue;
                }

                var targetEntry = targetTable.GetEntry(itemKey);
                if (targetEntry == null)
                {
                    targetTable.AddEntry(itemKey, itemText);
                    copiedNew++;
                }
                else if (targetEntry != null && overwriteExistingKeys)
                {
                    if (targetTable.RemoveEntry(itemKey))
                    {
                        targetTable.AddEntry(itemKey, itemText);
                        copiedOverwrite++;
                    }
                    else
                    {
                        Debug.LogErrorFormat("SplitQuestionnaireRecord() could not remove key '{0}'. Overwrite failed.", key);
                    }
                }
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Copies default Internal_Strings EN to all string tables in target collection.
        /// </summary>
        /// <param name="target">Target string table collection name.</param>
        /// <param name="overwriteExistingKeys">When true will overwrite existing keys with source string. When false existing keys are left unchanged.</param>
        public static void CopyInternalStringTable(string target, bool overwriteExistingKeys)
        {
            // Use default Internal_Strings collection with EN locale code as source
            string sourceCollectionName = TextManager.defaultInternalStringsCollectionName;
            string sourceLocaleCode     = enLocaleCode;

            // Do nothing if target not set
            if (string.IsNullOrEmpty(target))
            {
                return;
            }

            // Target cannot be same as default
            if (string.Compare(target, sourceCollectionName, true) == 0)
            {
                Debug.LogError("CopyInternalStringTable() target cannot be same as default");
                return;
            }

            // Get target string table collection
            var targetCollection = LocalizationEditorSettings.GetStringTableCollection(target);

            if (targetCollection == null)
            {
                Debug.LogErrorFormat("CopyInternalStringTable() could not find target string table collection '{0}'", target);
                return;
            }

            // Get source string table
            StringTable sourceTable = GetSourceStringTable(sourceCollectionName, sourceLocaleCode);

            if (!sourceTable)
            {
                Debug.LogErrorFormat("CopyInternalStringTable() could not find source table '{0}' with locale '{1}'", sourceCollectionName, sourceLocaleCode);
                return;
            }

            // Copy source strings to all tables in target collection
            int totalSourceEntries = sourceTable.SharedData.Entries.Count;
            int copiedNew          = 0;
            int copiedOverwrite    = 0;

            foreach (StringTable targetTable in targetCollection.StringTables)
            {
                // Iterate through all string table values found in source table
                foreach (var item in sourceTable.SharedData.Entries)
                {
                    string key         = item.Key;
                    var    sourceEntry = sourceTable.GetEntry(key);
                    if (sourceEntry == null)
                    {
                        Debug.LogWarningFormat("CopyInternalStringTable() could not find source table entry for key '{0}'", key);
                        continue;
                    }

                    var targetEntry = targetTable.GetEntry(key);
                    if (targetEntry == null)
                    {
                        targetTable.AddEntry(key, sourceEntry.Value);
                        copiedNew++;
                    }
                    else if (targetEntry != null && overwriteExistingKeys)
                    {
                        if (targetTable.RemoveEntry(key))
                        {
                            targetTable.AddEntry(key, sourceEntry.Value);
                            copiedOverwrite++;
                        }
                        else
                        {
                            Debug.LogErrorFormat("CopyInternalStringTable() could not remove key '{0}'. Overwrite failed.", key);
                        }
                    }
                }

                // Set table dirty
                EditorUtility.SetDirty(targetTable);
            }

            // Set target collection shared data dirty
            EditorUtility.SetDirty(targetCollection.SharedData);

            Debug.LogFormat("Source collection '{0}' has a total of {1} entries.\nTarget collection '{2}' received {3} new entries, {4} entries were overwritten.", sourceCollectionName, totalSourceEntries, target, copiedNew, copiedOverwrite);
        }
Esempio n. 8
0
    public static void ToJSON(string apiKey = "", bool upload = false)
    {
        var fileData = new Dictionary <string, StringContent>();

        foreach (StringTableCollection collection in LocalizationEditorSettings.GetStringTableCollections())
        {
            string collectionName = collection.TableCollectionName;

            // Only export english values
            //List<CultureInfo> cultures = GetCulturesInfo(collection);
            //foreach (var culture in cultures)
            //{

            var    culture = CultureInfo.GetCultureInfo("en");
            string folder  = Path.Combine(Application.dataPath, $"Locales/{culture.TwoLetterISOLanguageName}");
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            string path = Path.Combine(folder, $"{collectionName}.json");
            var    json = new JSONObject();

            StringTable table = (StringTable)collection.GetTable(culture);

            foreach (SharedTableData.SharedTableEntry entry in table.SharedData.Entries)
            {
                string key = entry.Key;

                if (table.GetEntry(key) == null || string.IsNullOrEmpty(table.GetEntry(key).Value))
                {
                    continue;
                }

                json[key] = table.GetEntry(key).Value;
            }

            if (upload)
            {
                fileData.Add($"{collectionName}.json", new StringContent(json.ToString(2)));
            }
            else
            {
                using (StreamWriter writer = new StreamWriter(path, false))
                    writer.Write(json.ToString(2));

                Debug.Log($"Wrote: {path}");
            }

            //}
        }

        if (upload)
        {
            string infoUrl   = $"https://api.crowdin.com/api/project/{projectIdentifier}/info?key={apiKey}&json=true";
            string actionUrl = $"https://api.crowdin.com/api/project/{projectIdentifier}/update-file?key={apiKey}";
            string addUrl    = $"https://api.crowdin.com/api/project/{projectIdentifier}/add-file?key={apiKey}";

            using (var formData = new MultipartFormDataContent())
                using (var formData2 = new MultipartFormDataContent())
                    using (var client = new HttpClient())
                    {
                        var infoTask = client.GetStringAsync(infoUrl);
                        infoTask.Wait();
                        var info = JSON.Parse(infoTask.Result);

                        var files = fileData.ToLookup(it => info["files"].AsArray.Children.Any(a => a["name"].Equals(it.Key)));

                        if (files[false].Any(_ => true))
                        {
                            foreach (var file in files[false])
                            {
                                Debug.Log($"Adding {file.Key}");
                                formData2.Add(file.Value, $"files[{file.Key}]", $"files[{file.Key}]");
                            }

                            var addTask = client.PostAsync(addUrl, formData2);
                            addTask.Wait();
                            var add = addTask.Result;

                            if (!add.IsSuccessStatusCode)
                            {
                                var why = add.Content.ReadAsStringAsync();
                                why.Wait();

                                Debug.Log($"Failed to add files to crowdin");
                                Debug.Log(why.Result);
                                return;
                            }
                        }

                        foreach (var file in files[true])
                        {
                            Debug.Log($"Updating {file.Key}");
                            formData.Add(file.Value, $"files[{file.Key}]", $"files[{file.Key}]");
                        }

                        var responseTask = client.PostAsync(actionUrl, formData);
                        responseTask.Wait();
                        var response = responseTask.Result;

                        if (!response.IsSuccessStatusCode)
                        {
                            var why = response.Content.ReadAsStringAsync();
                            why.Wait();

                            Debug.Log($"Failed to update crowdin");
                            Debug.Log(why.Result);
                        }
                        else
                        {
                            Debug.Log($"Uploaded files to crowdin");
                        }
                    }
        }
    }
Esempio n. 9
0
    public static void FromJSON(string apiKey = "", bool download = false)
    {
        string downloadUrl = $"https://api.crowdin.com/api/project/{projectIdentifier}/export-file?key={apiKey}";

        foreach (StringTableCollection collection in LocalizationEditorSettings.GetStringTableCollections())
        {
            string collectionName = collection.TableCollectionName;

            List <LocaleIdentifier> cultures = GetCulturesInfo(collection);
            foreach (var culture in cultures)
            {
                if (culture.Code.Equals("en"))
                {
                    continue;
                }

                string folder = Path.Combine(Application.dataPath, $"Locales/{culture.Code}");
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                string   path = Path.Combine(folder, $"{collectionName}.json");
                JSONNode json;
                if (download)
                {
                    using (var client = new HttpClient())
                    {
                        var downloadTask = client.GetAsync($"{downloadUrl}&file={collectionName}.json&language={culture.Code}");
                        try
                        {
                            downloadTask.Wait();
                            var stringTask = downloadTask.Result.Content.ReadAsStringAsync();
                            stringTask.Wait();
                            json = JSON.Parse(stringTask.Result);
                        }
                        catch (Exception)
                        {
                            // 404 = Import empty, anything else = skip
                            if (downloadTask.Result.StatusCode != System.Net.HttpStatusCode.NotFound)
                            {
                                continue;
                            }
                            json = new JSONObject();
                        }
                    }
                }
                else
                {
                    json = GetNodeFromFile(path);
                }

                StringTable table = (StringTable)collection.GetTable(culture);
                table.MetadataEntries.Clear();
                StringTable tableEnglish = (StringTable)collection.GetTable(CultureInfo.GetCultureInfo("en"));

                foreach (SharedTableData.SharedTableEntry entry in table.SharedData.Entries)
                {
                    string key = entry.Key;

                    if (json.HasKey(key))
                    {
                        table.AddEntry(key, json[key]);
                    }

                    if (table.GetEntry(key) == null || string.IsNullOrEmpty(table.GetEntry(key).Value))
                    {
                        // Add english as default
                        table.AddEntry(key, tableEnglish.GetEntry(key).Value);
                    }

                    table.GetEntry(key).IsSmart = false;
                    table.GetEntry(key).MetadataEntries.Clear();
                    table.GetEntry(key).IsSmart = tableEnglish.GetEntry(key).IsSmart;
                }

                EditorUtility.SetDirty(table);
                if (download)
                {
                    Debug.Log($"Downloaded: {culture.Code} - {collectionName}.json");
                }
                else
                {
                    Debug.Log($"Loaded: {path}");
                }
            }
        }

        AssetDatabase.SaveAssets();
    }
 public StringTableEntry GetEntry(StringTable table)
 {
     return(table.GetEntry(Key));
 }
Esempio n. 11
0
        public string Translate(string key)
        {
            var entry = _stringTable.GetEntry(key);

            return(entry != null ? entry.LocalizedValue : _stringTable.GetEntry(Error).LocalizedValue);
        }