Пример #1
0
        public IEnumerator ListViewUpdatesWhenLocaleIsRemoved()
        {
            WrapperWindow window = GetWindow((wnd) =>
            {
                // Perform an update
                var height = m_PropertyDrawer.GetPropertyHeight(m_Property, GUIContent.none);
                m_PropertyDrawer.OnGUI(new Rect(0, 0, 1000, height), m_Property, GUIContent.none);

                // Remove a locale
                var localeToRemove = m_FakeLocaleProvider.TestLocales[0];
                LocalizationEditorSettings.RemoveLocale(localeToRemove);
                Assert.That(m_FakeLocaleProvider.TestLocales, Does.Not.Contains(localeToRemove));

                // Update again, it should not contain the new element
                height = m_PropertyDrawer.GetPropertyHeight(m_Property, GUIContent.none);
                m_PropertyDrawer.OnGUI(new Rect(0, 0, 1000, height), m_Property, GUIContent.none);
                CheckListViewContainsProjectLocales();

                return(true);
            });

            yield return(null);

            Assert.That(window.TestCompleted, Is.True);
        }
Пример #2
0
        public IEnumerator ListViewUpdatesWhenLocaleIsAdded()
        {
            WrapperWindow window = GetWindow((wnd) =>
            {
                // Perform an update
                var height = m_PropertyDrawer.GetPropertyHeight(m_Property, GUIContent.none);
                m_PropertyDrawer.OnGUI(new Rect(wnd.position.x, wnd.position.y, wnd.position.width, height), m_Property, GUIContent.none);

                // Add a new Locale
                var newLocale = Locale.CreateLocale(SystemLanguage.Hebrew);
                LocalizationEditorSettings.AddLocale(newLocale);

                // Update again, it should not contain the new element
                height = m_PropertyDrawer.GetPropertyHeight(m_Property, GUIContent.none);
                m_PropertyDrawer.OnGUI(new Rect(wnd.position.x, wnd.position.y, wnd.position.width, height), m_Property, GUIContent.none);

                Assert.That(m_FakeLocaleProvider.TestLocales, Does.Contain(newLocale));
                CheckListViewContainsProjectLocales();

                return(true);
            });

            yield return(null);

            Assert.That(window.TestCompleted, Is.True);
        }
        /// <summary>
        /// IMGUI Version
        /// </summary>
        /// <param name="position"></param>
        /// <param name="property"></param>
        /// <param name="label"></param>
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            var code = property.FindPropertyRelative("m_Code");

            var foldRect = new Rect(position.x, position.y, EditorGUIUtility.labelWidth, EditorGUIUtility.singleLineHeight);

            property.isExpanded = EditorGUI.Foldout(foldRect, property.isExpanded, label, true);

            EditorGUI.BeginChangeCheck();
            EditorGUI.BeginProperty(foldRect, GUIContent.none, property);
            var localeRect        = new Rect(position.x + EditorGUIUtility.labelWidth, position.y, position.width - foldRect.width, foldRect.height);
            var newSelectedLocale = EditorGUI.ObjectField(localeRect, LocalizationEditorSettings.GetLocale(code.stringValue), typeof(Locale), false) as Locale;

            EditorGUI.EndProperty();
            if (EditorGUI.EndChangeCheck())
            {
                code.stringValue = newSelectedLocale != null ? newSelectedLocale.Identifier.Code : string.Empty;
            }

            if (property.isExpanded)
            {
                EditorGUI.indentLevel++;
                position.height = EditorGUIUtility.singleLineHeight;

                position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
                EditorGUI.PropertyField(position, code);
                EditorGUI.indentLevel--;
            }
        }
Пример #4
0
        /// <summary>
        /// Updates the Android Gradle project file with localized values using <see cref="AppInfo"/>.
        /// </summary>
        /// <param name="projectDirectory">The root project directory to be updated. This is where the Android player was built to.</param>
        /// <param name="appInfo">Contains the localized values for the App.</param>
        /// <param name="roundIconsInfo">Contains the localized values for Android Round Icon. Refer Android documentation for more details : https://developer.android.com/about/versions/nougat/android-7.1.html#circular-icons</param>
        /// <param name="legacyIconsInfo">Contains the localized values for Android Legacy Icon.</param>
        /// <param name="adaptiveIconsInfo">Contains the localized values for Android Adaptive Icon. . Refer Android documentation for more details : https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive</param>
        public static void AddLocalizationToAndroidGradleProject(string projectDirectory, AppInfo appInfo, RoundIconsInfo roundIconsInfo = null, LegacyIconsInfo legacyIconsInfo = null, AdaptiveIconsInfo adaptiveIconsInfo = null)
        {
            if (appInfo == null)
            {
                throw new ArgumentNullException(nameof(appInfo));
            }

            var project = new GradleProjectSettings();

            foreach (var locale in LocalizationEditorSettings.GetLocales())
            {
                var localeIdentifier = locale.Identifier.Code.Replace("-", "-r");
                GenerateLocalizedXmlFile("App Name", Path.Combine(Directory.CreateDirectory(Path.Combine(project.GetResFolderPath(projectDirectory), "values-b+" + localeIdentifier)).FullName, k_InfoFile), locale, appInfo);

                //Generate icons
                var folderNames = new List <string>
                {
                    $"mipmap-{localeIdentifier}-hdpi",
                    $"mipmap-{localeIdentifier}-ldpi",
                    $"mipmap-{localeIdentifier}-mdpi",
                    $"mipmap-{localeIdentifier}-xhdpi",
                    $"mipmap-{localeIdentifier}-xxhdpi",
                    $"mipmap-{localeIdentifier}-xxxhdpi",
                    $"mipmap-{localeIdentifier}-anydpi-v26"
                };


                if (roundIconsInfo != null || legacyIconsInfo != null || adaptiveIconsInfo != null)
                {
                    GenerateIconDirectory(folderNames, project.GetResFolderPath(projectDirectory), locale);
                }

                if (roundIconsInfo != null)
                {
                    GenerateRoundIcons(folderNames, project.GetResFolderPath(projectDirectory), locale, roundIconsInfo);
                }

                if (legacyIconsInfo != null)
                {
                    GenerateLegacyIcons(folderNames, project.GetResFolderPath(projectDirectory), locale, legacyIconsInfo);
                }

                if (adaptiveIconsInfo != null)
                {
                    GenerateAdaptiveIcons(folderNames, project.GetResFolderPath(projectDirectory), locale, adaptiveIconsInfo);
                }
            }

            var androidManifest = new AndroidManifest(project.GetManifestPath(projectDirectory));

            androidManifest.SetAtrribute("label", project.LabelName);

            if (adaptiveIconsInfo != null || legacyIconsInfo != null || roundIconsInfo != null)
            {
                androidManifest.SetAtrribute("icon", project.IconLabelName);
                androidManifest.SetAtrribute("roundIcon", project.RoundIconLabelName);
            }

            androidManifest.SaveIfModified();
        }
    /// <summary>
    /// Gets the localized string from an already loaded table, taking into account whether we are in edit mode, play mode, or a build.
    /// </summary>
    /// <param name="localizedStringReference">The <see cref="LocalizedString"/>.</param>
    /// <returns>The localized string.</returns>

    public static string GetLocalizedStringImmediateSafe(this LocalizedString localizedStringReference)
    {
        // If we are in the editor in edit mode, we need to find a valid locale and get the localized string from it:
#if UNITY_EDITOR
        if (EditorApplication.isPlaying)
        {
            return(string.Empty);
        }

        string text = null;
        if (!localizedStringReference.IsEmpty)
        {
            var    tableCollection = LocalizationEditorSettings.GetStringTableCollection(localizedStringReference.TableReference);
            Locale locale          = Editor_GetValidLocaleInEditMode(tableCollection);
            if (locale != null)
            {
                StringTable table = (StringTable)tableCollection.GetTable(locale.Identifier);
                if (table != null)
                {
                    if (table.GetEntryFromReference(localizedStringReference.TableEntryReference) != null)
                    {
                        text = table.GetEntryFromReference(localizedStringReference.TableEntryReference).LocalizedValue;
                    }
                }
            }
        }
        return(text);
#else
        // At runtime (build or editor in play mode), we just get the localized string normally:
        return(localizedStringReference.GetLocalizedString());
#endif
    }
Пример #6
0
    public void SetupTableOverrideInEditor()
    {
        // Get the 2 table collections. 1 for default and 1 for our chosen platform (PS4).
        var collection    = LocalizationEditorSettings.GetStringTableCollection("My Strings");
        var collectionPs4 = LocalizationEditorSettings.GetStringTableCollection("My Strings PS4");

        var englishTable    = collection.GetTable("en") as StringTable;
        var englishTablePs4 = collectionPs4.GetTable("en") as StringTable;

        // Add the default entry
        var entry = englishTable.AddEntry("COPYRIGHT_NOTICE", "This is some copyright info for general platforms...");

        // Add the entry we want to use on PS4 using the same entry name.
        englishTablePs4.AddEntry("COPYRIGHT_NOTICE", "This is some copyright info for PS4 platforms...");

        // Set up the platform override so that COPYRIGHT_NOTICE redirects to a different table but uses the same key.
        var platformOverride = new PlatformOverride();

        platformOverride.AddPlatformTableOverride(RuntimePlatform.PS4, "My Strings PS4");
        entry.SharedEntry.Metadata.AddMetadata(platformOverride);

        // Mark the assets dirty so changes are saved
        EditorUtility.SetDirty(collection.SharedData);
        EditorUtility.SetDirty(englishTable);
    }
Пример #7
0
        void ResolveTableCollection()
        {
            m_PossibleTableCollection.Clear();
            m_Collection = LocalizationEditorSettings.GetCollectionFromTable(m_TargetTable);

            if (m_TargetTable.SharedData == null)
            {
                return;
            }

            m_SharedTableDataSerializedObject = new SerializedObject(m_TargetTable.SharedData);
            m_TableCollectionName             = m_SharedTableDataSerializedObject.FindProperty("m_TableCollectionName");

            if (m_Collection != null)
            {
                m_CollectionButton = new GUIContent("Select Collection", EditorGUIUtility.ObjectContent(m_Collection, m_Collection.GetType()).image);
                return;
            }

            m_SharedTableDataCollection = LocalizationEditorSettings.GetCollectionForSharedTableData(m_TargetTable.SharedData);
            if (m_SharedTableDataCollection != null)
            {
                return;
            }

            LocalizationEditorSettings.FindLooseStringTablesUsingSharedTableData(m_TargetTable.SharedData, m_PossibleTableCollection);
        }
Пример #8
0
        private void Reset()
        {
            //Set up Unity Event automatically
            var target         = GetComponent <TextMeshProUGUI>();
            var setFontMethod  = target.GetType().GetProperty("font").GetSetMethod();
            var methodDelegate = System.Delegate.CreateDelegate(typeof(UnityAction <TMP_FontAsset>), target, setFontMethod) as UnityAction <TMP_FontAsset>;

            UnityEditor.Events.UnityEventTools.AddPersistentListener(this.OnUpdateAsset, methodDelegate);

            //Set up font localize asset table automatically
            var collections = LocalizationEditorSettings.GetAssetTableCollections();

            foreach (var tableCollection in collections)
            {
                if (tableCollection.name == "Fonts")
                {
                    this.AssetReference.TableReference = tableCollection.TableCollectionNameReference;
                    foreach (var entry in tableCollection.SharedData.Entries)
                    {
                        if (entry.Key == "font")
                        {
                            this.AssetReference.TableEntryReference = entry.Id;
                        }
                    }
                }
            }
        }
Пример #9
0
        void RefreshTables()
        {
            // Find loose tables
            m_LooseTables.Clear();

            if (m_Collection.SharedData == null)
            {
                return;
            }

            LocalizationEditorSettings.FindLooseStringTablesUsingSharedTableData(m_Collection.SharedData, m_LooseTables);

            // Find missing tables by project locales
            var projectLocales = LocalizationEditorSettings.GetLocales();

            m_MissingTables.Clear();
            foreach (var locale in projectLocales)
            {
                if (!m_Collection.ContainsTable(locale.Identifier))
                {
                    m_MissingTables.Add(locale);
                }
            }

            Repaint();
        }
        public static Locale GetLocaleFallback(Locale locale)
        {
            // Use fallback?
            var fallBackLocale = locale.Metadata?.GetMetadata <FallbackLocale>()?.Locale;

            if (fallBackLocale != null)
            {
                return(fallBackLocale);
            }

            var cultureInfo = locale.Identifier.CultureInfo;

            if (cultureInfo == null)
            {
                return(fallBackLocale);
            }

            while (cultureInfo != CultureInfo.InvariantCulture && fallBackLocale == null)
            {
                var fb = LocalizationEditorSettings.GetLocale(new LocaleIdentifier(cultureInfo).Code);
                if (locale != fb)
                {
                    fallBackLocale = fb;
                }
                cultureInfo = cultureInfo.Parent;
            }

            return(fallBackLocale);
        }
        public static void PullEnglish()
        {
            // Setup the connection to Google
            var sheetServiceProvider = GetServiceProvider();
            var googleSheets         = new GoogleSheets(sheetServiceProvider);

            googleSheets.SpreadSheetId = "My spread sheet id"; // We need to provide the Spreadsheet id. This can be found in the url. See docs for further info.

            // You should provide your String Table Collection name here
            var tableCollection = LocalizationEditorSettings.GetStringTableCollection("My Strings");

            // We need configure what each column contains in the sheet
            var columnMappings = new SheetColumn[]
            {
                // Column A contains the Key
                new KeyColumn {
                    Column = "A"
                },

                // Column B contains any shared comments. These are Comment Metadata in the Shared category.
                new KeyCommentColumn {
                    Column = "B"
                },

                // Column C contains the English Locale and any comments that are just for this Locale.
                new LocaleColumn {
                    Column = "C", LocaleIdentifier = "en", IncludeComments = true
                },
            };

            int mySheetId = 123456; // This it the id of the sheet in the Google Spreadsheet. it will be in the url after `gid=`.

            googleSheets.PullIntoStringTableCollection(mySheetId, tableCollection, columnMappings);
        }
Пример #12
0
        static void ImportStringTable(MenuCommand command)
        {
            var table = command.context as StringTable;

            Assert.IsTrue(table != null, "Expected StringTable");

            var path = EditorUtility.OpenFilePanel($"Import CSV into {table.TableData}({table.LocaleIdentifier})", PreviousDirectory, "csv");

            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            EditorPrefs.SetString(kPrefFile, path);

            var collection = LocalizationEditorSettings.GetCollectionFromTable(table) as StringTableCollection;

            if (collection == null)
            {
                Debug.LogError("String Table must belong to a StringTableCollection.");
                return;
            }

            var cellMappings = new CsvColumns[] { new KeyIdColumns(), new LocaleColumns {
                                                      LocaleIdentifier = table.LocaleIdentifier
                                                  } };

            using (var stream = new StreamReader(path))
            {
                var reporter = TaskReporter.CreateDefaultReporter();
                reporter.Start("Importing " + path, string.Empty);
                Csv.ImportInto(stream, collection, cellMappings, true, reporter);
            }
        }
Пример #13
0
        private static MonoBehaviour SetupForFontLocalization(TextMeshProUGUI target)
        {
            //Avoid adding the component multiple times
            if (target.GetComponent <LocalizeTMProFontEvent>() != null)
            {
                return(null);
            }

            var comp           = Undo.AddComponent(target.gameObject, typeof(LocalizeTMProFontEvent)) as LocalizeTMProFontEvent;
            var setFontMethod  = target.GetType().GetProperty("font").GetSetMethod();
            var methodDelegate = System.Delegate.CreateDelegate(typeof(UnityAction <TMP_FontAsset>), target, setFontMethod) as UnityAction <TMP_FontAsset>;

            Events.UnityEventTools.AddPersistentListener(comp.OnUpdateAsset, methodDelegate);

            //Find font table and set it up automatically
            var collections = LocalizationEditorSettings.GetAssetTableCollections();

            foreach (var tableCollection in collections)
            {
                if (tableCollection.name == "Fonts")
                {
                    comp.AssetReference.TableReference = tableCollection.TableCollectionNameReference;
                    foreach (var entry in tableCollection.SharedData.Entries)
                    {
                        if (entry.Key == "font")
                        {
                            comp.AssetReference.TableEntryReference = entry.Id;
                        }
                    }
                }
            }

            return(null);
        }
        public IEnumerator ListViewUpdatesWhenLocaleIsAdded()
        {
            bool          localeAdded = false;
            WrapperWindow window      = GetWindow((wnd) =>
            {
                // Add a new Locale
                if (!localeAdded)
                {
                    var newLocale = Locale.CreateLocale(SystemLanguage.Hebrew);
                    LocalizationEditorSettings.AddLocale(newLocale);
                    Assert.That(m_FakeLocaleProvider.TestLocales, Does.Contain(newLocale));
                    localeAdded = true;
                    return(false);
                }
                else
                {
                    CheckListContainsProjectLocales(wnd);
                    return(true);
                }
            });

            var root = m_PropertyDrawer.CreatePropertyGUI(m_ScriptableObject.FindProperty("provider"));

            window.rootVisualElement.Add(root);

            yield return(null);

            Assert.That(window.TestCompleted, Is.True);
        }
        public TableCreator()
        {
            var asset = Resources.GetTemplateAsset(nameof(TableCreator));

            asset.CloneTree(this);

            var locales = LocalizationEditorSettings.GetLocales();

            m_LocalesList = this.Q <ScrollView>("locales-list");
            foreach (var locale in locales)
            {
                AddLocaleElement(locale);
            }

            m_CreateStringTablesButton = this.Q <Button>("create-string-tables-button");
            m_CreateStringTablesButton.clickable.clicked += () => CreateCollection(LocalizationEditorSettings.CreateStringTableCollection);

            m_CreateAssetTablesButton = this.Q <Button>("create-asset-tables-button");
            m_CreateAssetTablesButton.clickable.clicked += () => CreateCollection(LocalizationEditorSettings.CreateAssetTableCollection);

            UpdateCreateButtonState();

            this.Q <Button>("select-all-button").clickable.clicked       += () => SelectAllLocales(true);
            this.Q <Button>("select-none-button").clickable.clicked      += () => SelectAllLocales(false);
            this.Q <Button>("locale-generator-button").clickable.clicked += () => LocaleGeneratorWindow.ShowWindow();

            m_TableCollectionName = this.Q <TextField>("new-table-name-field");

            LocalizationEditorSettings.EditorEvents.LocaleAdded   += OnLocaleAdded;
            LocalizationEditorSettings.EditorEvents.LocaleRemoved += OnLocaleRemoved;
        }
Пример #16
0
        static void WriteLocalizedValue(string valueName, StreamWriter stream, Locale locale, LocalizedString localizedString, PlistDocument plistDocument)
        {
            if (localizedString.IsEmpty)
            {
                return;
            }

            var tableCollection = LocalizationEditorSettings.GetStringTableCollection(localizedString.TableReference);
            var table           = tableCollection?.GetTable(locale.Identifier) as StringTable;
            var entry           = table?.GetEntryFromReference(localizedString.TableEntryReference);

            if (entry == null || string.IsNullOrWhiteSpace(entry.LocalizedValue))
            {
                // Use fallback?
                var fallBack = FallbackLocaleHelper.GetLocaleFallback(locale);
                if (fallBack != null)
                {
                    WriteLocalizedValue(valueName, stream, fallBack, localizedString, plistDocument);
                    return;
                }

                Debug.LogWarning($"{valueName}: Could not find a localized value for {locale} from {localizedString}");
                return;
            }

            Debug.Assert(!entry.IsSmart, $"Localized App Values ({valueName}) do not support Smart Strings - {localizedString}");
            stream.WriteLine($"\"{valueName}\" = \"{entry.LocalizedValue}\";");

            plistDocument.root.SetString(valueName, string.Empty);
        }
        void CreateCollection()
        {
            var assetDirectory = EditorUtility.SaveFolderPanel("Create Table Collection", "Assets/", "");

            if (string.IsNullOrEmpty(assetDirectory))
            {
                return;
            }

            LocalizationTableCollection createdCollection = null;

            if (m_CollectionTypePopup.value == typeof(StringTableCollection))
            {
                createdCollection = LocalizationEditorSettings.CreateStringTableCollection(m_TableCollectionName.value, assetDirectory, GetSelectedLocales());
            }
            if (m_CollectionTypePopup.value == typeof(AssetTableCollection))
            {
                createdCollection = LocalizationEditorSettings.CreateAssetTableCollection(m_TableCollectionName.value, assetDirectory, GetSelectedLocales());
            }

            // Select the root asset and open the table editor window.
            Selection.activeObject = createdCollection;
            LocalizationTablesWindow.ShowWindow(createdCollection);
            InitializeTableName();
        }
Пример #18
0
        public void AddLocale_WithNonPersistentLocale_GeneratesError()
        {
            var locale = ScriptableObject.CreateInstance <Locale>();

            Assert.Throws <AssetNotPersistentException>(() => LocalizationEditorSettings.AddLocale(locale));
            Object.DestroyImmediate(locale);
        }
Пример #19
0
    public void RemoveLineFromSharedTable()
    {
        StringTableCollection collection = LocalizationEditorSettings.GetStringTableCollection("Questline Dialogue");

        if (collection != null)
        {
            int             index         = 0;
            LocalizedString _dialogueLine = null;



            do
            {
                index++;
                string key = "L" + index + "-" + this.name;

                if (collection.SharedData.Contains(key))
                {
                    collection.SharedData.RemoveKey(key);
                }
                else
                {
                    _dialogueLine = null;
                }
            } while (_dialogueLine != null);
        }
    }
Пример #20
0
        private void Initialize()
        {
            if (ID != UInt32.MaxValue && childId != UInt32.MaxValue)
            {
                // Only get the first dialogue.
                startDialogue = DialogueLine.ConvertRow(TableDatabase.Get.GetRow("dialogues", childId),
                                                        overrideTable ? collection : LocalizationEditorSettings.GetStringTableCollection("Dialogues"));

                var field = TableDatabase.Get.GetField(Name, "data", ID);
                if (field != null)
                {
                    StoryTable.ParseNodeData(this, (JObject)field.Data);
                }
            }

            if (characterID != UInt32.MaxValue)
            {
                TableDatabase          database = TableDatabase.Get;
                Tuple <uint, TableRow> link     = database.FindLink("characters", "name", characterID);
                if (link != null)
                {
                    var field = database.GetField(link.Item2, "name");
                    if (field != null)
                    {
                        characterName = (string)field.Data;
                    }

                    Debug.Log(characterName);
                }
            }
        }
Пример #21
0
    void SetDialogueLines()
    {
        _dialogueLines.Clear();

        StringTableCollection collection = LocalizationEditorSettings.GetStringTableCollection("Questline Dialogue");

        if (collection != null)
        {
            int             index         = 0;
            LocalizedString _dialogueLine = null;
            do
            {
                index++;
                string key = "L" + index + "-" + this.name;

                if (collection.SharedData.Contains(key))
                {
                    _dialogueLine = new LocalizedString()
                    {
                        TableReference = "Questline Dialogue", TableEntryReference = key
                    };
                    _dialogueLines.Add(_dialogueLine);
                }
                else
                {
                    _dialogueLine = null;
                }
            } while (_dialogueLine != null);
        }
    }
Пример #22
0
        // Gets string table from collection name and locale code
        private static StringTable GetSourceStringTable(string source, string locale)
        {
            // Get source string table collection
            var sourceCollection = LocalizationEditorSettings.GetStringTableCollection(source);

            if (sourceCollection == null)
            {
                Debug.LogErrorFormat("GetSourceStringTable() could not find source string table collection '{0}'", source);
                return(null);
            }

            // Find table in source collection with locale code
            StringTable sourceTable = null;

            foreach (StringTable table in sourceCollection.StringTables)
            {
                if (table.LocaleIdentifier == locale)
                {
                    sourceTable = table;
                    break;
                }
            }

            // Handle table not found
            if (sourceTable == null)
            {
                Debug.LogErrorFormat("GetSourceStringTable() could not find source string table with locale code '{0}' in collection '{1}'", locale, source);
                return(null);
            }

            return(sourceTable);
        }
Пример #23
0
        private static MonoBehaviour SetupForStringLocalization(TextMeshProUGUI target)
        {
            //Avoid adding the component multiple times
            if (target.GetComponent <LocalizeStringEvent>() != null)
            {
                return(null);
            }

            var comp            = Undo.AddComponent(target.gameObject, typeof(LocalizeStringEvent)) as LocalizeStringEvent;
            var setStringMethod = target.GetType().GetProperty("text").GetSetMethod();
            var methodDelegate  = System.Delegate.CreateDelegate(typeof(UnityAction <string>), target, setStringMethod) as UnityAction <string>;

            Events.UnityEventTools.AddPersistentListener(comp.OnUpdateString, methodDelegate);

            const int kMatchThreshold = 5;
            var       foundKey        = LocalizationEditorSettings.FindSimilarKey(target.text);

            if (foundKey.collection != null && foundKey.matchDistance < kMatchThreshold)
            {
                comp.StringReference.TableEntryReference = foundKey.entry.Id;
                comp.StringReference.TableReference      = foundKey.collection.TableCollectionNameReference;
            }

            return(null);
        }
        void CheckListContainsProjectLocales(WrapperWindow wnd)
        {
            var listScrollView = wnd.rootVisualElement.Q <ReorderableList>().Q <ScrollView>();
            var locales        = LocalizationEditorSettings.GetLocales().ToList();

            Assert.AreEqual(locales.Count, listScrollView.childCount, "Expected list size to match the number of project locales.");

            int localeCount = locales.Count;

            for (int i = 0; i < localeCount; ++i)
            {
                var item = listScrollView[i];
                var name = item.Q <TextField>("name");
                var code = item.Q <TextField>("code");

                Assert.NotNull(name, "Could not find name field.");
                Assert.NotNull(code, "Could not find code field.");

                var matchingLocale = locales.FirstOrDefault(l => l.name == name.value);
                Assert.NotNull(matchingLocale, $"Could not find a matching locale for {name.value}({code.value})");
                locales.Remove(matchingLocale);
            }

            Assert.That(locales, Is.Empty, "Expected all project locales to be in the ListView but they were not.");
        }
Пример #25
0
        void DrawLooseTableGUI()
        {
            if (m_TargetTable.SharedData == null)
            {
                EditorGUILayout.HelpBox("Shared Table Data is missing. Please add the missing asset or create a new one.", MessageType.Error);
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.ObjectField(m_SharedTableData);
                if (EditorGUI.EndChangeCheck())
                {
                    ResolveTableCollection();
                }
                return;
            }

            EditorGUILayout.HelpBox("Table does not belong to a Collection and will be ignored.", MessageType.Warning);
            if (m_SharedTableDataCollection != null)
            {
                if (GUILayout.Button(Styles.addToCollection))
                {
                    m_SharedTableDataCollection.AddTable(m_TargetTable, createUndo: true);
                }
                return;
            }

            if (m_PossibleTableCollection.Count > 0)
            {
                EditorGUILayout.Space();
                EditorGUILayout.HelpBox("The following loose tables could be combined into a new Table Collection", MessageType.Info);
                for (int i = 0; i < m_PossibleTableCollection.Count; ++i)
                {
                    EditorGUILayout.BeginHorizontal();
                    if (GUILayout.Button(m_PossibleTableCollection[i].name, EditorStyles.label))
                    {
                        EditorGUIUtility.PingObject(m_PossibleTableCollection[i]);
                    }
                    if (GUILayout.Button(Styles.removeTableFromList, GUILayout.Width(40)))
                    {
                        m_PossibleTableCollection.RemoveAt(i);
                        EditorGUIUtility.ExitGUI();
                    }
                    EditorGUILayout.EndHorizontal();
                }
            }

            if (m_PossibleTableCollection.Count > 0)
            {
                var isStringTable = typeof(StringTable).IsAssignableFrom(m_PossibleTableCollection[0].GetType());
                var label         = isStringTable ? Styles.createStringTableCollection : Styles.createAssetTableCollection;
                if (GUILayout.Button(label))
                {
                    var defaultDirectory = Path.GetDirectoryName(AssetDatabase.GetAssetPath(m_TargetTable.SharedData));
                    var path             = EditorUtility.SaveFilePanel("Create Table Collection", defaultDirectory, m_TargetTable.TableCollectionName, "asset");
                    if (string.IsNullOrEmpty(path))
                    {
                        return;
                    }
                    LocalizationEditorSettings.CreateCollectionFromLooseTables(m_PossibleTableCollection, path);
                }
            }
        }
Пример #26
0
        protected override TreeViewItem BuildRoot()
        {
            var root = new TreeViewItem(-1, -1);
            var id   = 1;

            root.AddChild(new TableEntryTreeViewItem(null, null, id++, 0)
            {
                displayName = $"None ({m_AssetType.Name})"
            });

            if (m_AssetType == typeof(string))
            {
                var stringTableCollections = LocalizationEditorSettings.GetStringTableCollections();
                foreach (var collection in stringTableCollections)
                {
                    var tableNode = new TreeViewItem(id++, 0, collection.TableCollectionName)
                    {
                        icon = AssetDatabase.GetCachedIcon(AssetDatabase.GetAssetPath(collection)) as Texture2D
                    };
                    root.AddChild(tableNode);

                    var sharedData = collection.SharedData;
                    foreach (var entry in sharedData.Entries)
                    {
                        tableNode.AddChild(new TableEntryTreeViewItem(collection, entry, id++, 1));
                    }
                }
            }
            else
            {
                var assetTableCollections = LocalizationEditorSettings.GetAssetTableCollections();
                foreach (var collection in assetTableCollections)
                {
                    var tableNode = new TreeViewItem(id++, 0, collection.TableCollectionName)
                    {
                        icon = AssetDatabase.GetCachedIcon(AssetDatabase.GetAssetPath(collection)) as Texture2D
                    };
                    root.AddChild(tableNode);

                    // Only show keys that have a compatible type.
                    var sharedData = collection.SharedData;
                    foreach (var entry in sharedData.Entries)
                    {
                        var typeMetadata = entry.Metadata.GetMetadata <AssetTypeMetadata>();
                        if (typeMetadata == null || m_AssetType.IsAssignableFrom(typeMetadata.Type))
                        {
                            tableNode.AddChild(new TableEntryTreeViewItem(collection, entry, id++, 1));
                        }
                    }
                }
            }

            if (!root.hasChildren)
            {
                root.AddChild(new TreeViewItem(1, 0, "No Tables Found."));
            }

            return(root);
        }
    public LocalizedString GenerateLocalizedStringInEditor()
    {
        // The main advantage to using a table Guid and entry Id is that references will not be lost when changes are made to the Table name or Entry name.
        var collection = LocalizationEditorSettings.GetStringTableCollection("My String Table");
        var entry      = collection.SharedData.GetEntry("Start Game");

        return(new LocalizedString(collection.SharedData.TableCollectionNameGuid, entry.Id));
    }
 static List <Locale> GetChoices()
 {
     s_Locales.Clear();
     s_Locales.Add(null);
     s_Locales.AddRange(LocalizationEditorSettings.GetLocales());
     s_Locales.AddRange(LocalizationEditorSettings.GetPsuedoLocales());
     return(s_Locales);
 }
Пример #29
0
 static void UpdateList(ReorderableList list)
 {
     list.List.Clear();
     foreach (var locale in LocalizationEditorSettings.GetLocales())
     {
         list.List.Add(locale);
     }
 }
        /// <summary>
        /// This example show how to import a collection with default settings.
        /// </summary>
        public static void SimpleImport()
        {
            var collection = LocalizationEditorSettings.GetStringTableCollection("My Strings");

            using (var stream = new StreamReader("My Strings CSV.csv"))
            {
                Csv.ImportInto(stream, collection);
            }
        }