Example #1
0
 public static bool CanTranslate()
 {
     return(LocalizationManager.Sources.Count > 0 &&
            !string.IsNullOrEmpty(LocalizationManager.GetWebServiceURL()));
 }
Example #2
0
        public void OnLocalize(bool Force = false)
        {
            if (!Force && (!enabled || gameObject == null || !gameObject.activeInHierarchy))
            {
                return;
            }

            if (string.IsNullOrEmpty(LocalizationManager.CurrentLanguage))
            {
                return;
            }

            if (!AlwaysForceLocalize && !Force && !LocalizeCallBack.HasCallback() && LastLocalizedLanguage == LocalizationManager.CurrentLanguage)
            {
                return;
            }
            LastLocalizedLanguage = LocalizationManager.CurrentLanguage;

            if (!HasTargetCache())
            {
                FindTarget();
            }

            if (!HasTargetCache())
            {
                return;
            }

            // These are the terms actually used (will be mTerm/mSecondaryTerm or will get them from the objects if those are missing. e.g. Labels' text and font name)
            if (string.IsNullOrEmpty(FinalTerm) || string.IsNullOrEmpty(FinalSecondaryTerm))
            {
                GetFinalTerms(out FinalTerm, out FinalSecondaryTerm);
            }


            bool hasCallback = Application.isPlaying && LocalizeCallBack.HasCallback();

            if (!hasCallback && string.IsNullOrEmpty(FinalTerm) && string.IsNullOrEmpty(FinalSecondaryTerm))
            {
                return;
            }

            CallBackTerm          = FinalTerm;
            CallBackSecondaryTerm = FinalSecondaryTerm;
            MainTranslation       = LocalizationManager.GetTermTranslation(FinalTerm, false);
            SecondaryTranslation  = LocalizationManager.GetTermTranslation(FinalSecondaryTerm, false);

            if (!hasCallback && string.IsNullOrEmpty(MainTranslation) && string.IsNullOrEmpty(SecondaryTranslation))
            {
                return;
            }

            CurrentLocalizeComponent = this;
            if (Application.isPlaying)
            {
                LocalizeCallBack.Execute(this);                   // This allows scripts to modify the translations :  e.g. "Player {0} wins"  ->  "Player Red wins"
                LocalizationManager.ApplyLocalizationParams(ref MainTranslation, gameObject);
            }

            if (LocalizationManager.IsRight2Left && !IgnoreRTL)
            {
                if (AllowMainTermToBeRTL && !string.IsNullOrEmpty(MainTranslation))
                {
                    MainTranslation = LocalizationManager.ApplyRTLfix(MainTranslation, MaxCharactersInRTL, IgnoreNumbersInRTL);
                }
                if (AllowSecondTermToBeRTL && !string.IsNullOrEmpty(SecondaryTranslation))
                {
                    SecondaryTranslation = LocalizationManager.ApplyRTLfix(SecondaryTranslation);
                }
            }
            switch (PrimaryTermModifier)
            {
            case TermModification.ToUpper: MainTranslation = MainTranslation.ToUpper(); break;

            case TermModification.ToLower: MainTranslation = MainTranslation.ToLower(); break;

            case TermModification.ToUpperFirst: MainTranslation = GoogleTranslation.UppercaseFirst(MainTranslation); break;

            case TermModification.ToTitle: MainTranslation = GoogleTranslation.TitleCase(MainTranslation); break;
            }
            switch (SecondaryTermModifier)
            {
            case TermModification.ToUpper: SecondaryTranslation = SecondaryTranslation.ToUpper();  break;

            case TermModification.ToLower: SecondaryTranslation = SecondaryTranslation.ToLower();  break;

            case TermModification.ToUpperFirst: SecondaryTranslation = GoogleTranslation.UppercaseFirst(SecondaryTranslation); break;

            case TermModification.ToTitle: SecondaryTranslation = GoogleTranslation.TitleCase(SecondaryTranslation); break;
            }
            EventDoLocalize(MainTranslation, SecondaryTranslation);
            CurrentLocalizeComponent = null;
        }
        public static void ApplyLocalizationParams(ref string translation, _GetParam getParam, bool allowLocalizedParameters = true)
        {
            if (translation == null)
            {
                return;
            }

            string pluralType = null;
            int    idx0       = 0;
            int    idx1       = translation.Length;

            int index = 0;

            while (index >= 0 && index < translation.Length)
            {
                int iParamStart = translation.IndexOf("{[", index);
                if (iParamStart < 0)
                {
                    break;
                }

                int iParamEnd = translation.IndexOf("]}", iParamStart);
                if (iParamEnd < 0)
                {
                    break;
                }

                // there is a sub param, so, skip this one:   "this {[helo{[hi]} end"
                int isubParam = translation.IndexOf("{[", iParamStart + 1);
                if (isubParam > 0 && isubParam < iParamEnd)
                {
                    index = isubParam;
                    continue;
                }

                // Check that some plural parameters can have the form: {[#name]}
                var offset = translation[iParamStart + 2] == '#' ? 3 : 2;
                var param  = translation.Substring(iParamStart + offset, iParamEnd - iParamStart - offset);
                var result = (string)getParam(param);
                if (result != null && allowLocalizedParameters)
                {
                    // check if Param is Localized
                    LanguageSourceData source;
                    var termData = LocalizationManager.GetTermData(result, out source);
                    if (termData != null)
                    {
                        int idx = source.GetLanguageIndex(LocalizationManager.CurrentLanguage);
                        if (idx >= 0)
                        {
                            result = termData.GetTranslation(idx);
                        }
                    }

                    var paramTag = translation.Substring(iParamStart, iParamEnd - iParamStart + 2);
                    translation = translation.Replace(paramTag, result);

                    int amount = 0;
                    if (int.TryParse(result, out amount))
                    {
                        pluralType = GoogleLanguages.GetPluralType(CurrentLanguageCode, amount).ToString();
                    }

                    index = iParamStart + result.Length;
                }
                else
                {
                    index = iParamEnd + 2;
                }
            }

            if (pluralType != null)
            {
                var tag = "[i2p_" + pluralType + "]";
                idx0 = translation.IndexOf(tag, System.StringComparison.OrdinalIgnoreCase);
                if (idx0 < 0)
                {
                    idx0 = 0;
                }
                else
                {
                    idx0 += tag.Length;
                }

                idx1 = translation.IndexOf("[i2p_", idx0 + 1, System.StringComparison.OrdinalIgnoreCase);
                if (idx1 < 0)
                {
                    idx1 = translation.Length;
                }

                translation = translation.Substring(idx0, idx1 - idx0);
            }
        }
 public static string Get(string Term, bool FixForRTL)
 {
     return(LocalizationManager.GetTermTranslation(Term, FixForRTL, 0, false));
 }
 public static string Get(string Term, bool FixForRTL, int maxLineLengthForRTL, bool ignoreNumbers)
 {
     return(LocalizationManager.GetTermTranslation(Term, FixForRTL, maxLineLengthForRTL, ignoreNumbers));
 }
Example #6
0
 public bool HasGoogleSpreadsheet()
 {
     return(!string.IsNullOrEmpty(LocalizationManager.GetWebServiceURL(this)) && !string.IsNullOrEmpty(Google_SpreadsheetKey));// && !string.IsNullOrEmpty(Google_SpreadsheetName);
 }
        public override void OnInspectorGUI()
        {
            Undo.RecordObject(target, "Localize");

            GUI.backgroundColor = Color.Lerp(Color.black, Color.gray, 1);
            GUILayout.BeginVertical(GUIStyle_Background, GUILayout.Height(1));
            GUI.backgroundColor = Color.white;

            if (GUILayout.Button("Localize", GUIStyle_Header))
            {
                Application.OpenURL(HelpURL_Documentation);
            }
            GUILayout.Space(-10);

            LocalizationManager.UpdateSources();

            if (LocalizationManager.Sources.Count == 0)
            {
                EditorGUILayout.HelpBox("Unable to find a Language Source.", MessageType.Warning);
            }
            else
            {
                GUILayout.Space(10);
                OnGUI_Target();
                GUILayout.Space(10);
                OnGUI_Terms();

                //if (mGUI_ShowTems || mGUI_ShowReferences) GUILayout.Space(5);

                OnGUI_References();

                if (mGUI_ShowReferences || mGUI_ShowCallback)
                {
                    GUILayout.Space(10);
                }

                Localize loc = target as Localize;

                //--[ Localize Callback ]----------------------
                string HeaderTitle = "On Localize Call:";
                if (!mGUI_ShowCallback && loc.LocalizeCallBack.Target != null && !string.IsNullOrEmpty(loc.LocalizeCallBack.MethodName))
                {
                    HeaderTitle = string.Concat(HeaderTitle, " <b>", loc.LocalizeCallBack.Target.name, ".</b><i>", loc.LocalizeCallBack.MethodName, "</i>");
                }
                mGUI_ShowCallback = GUITools.DrawHeader(HeaderTitle, mGUI_ShowCallback);
                if (mGUI_ShowCallback)
                {
                    GUITools.BeginContents();
                    DrawEventCallBack(loc.LocalizeCallBack, loc);
                    GUITools.EndContents();
                }
            }
            OnGUI_Source();

            GUILayout.Space(10);

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("v" + LocalizationManager.GetVersion(), EditorStyles.miniLabel))
            {
                Application.OpenURL(LocalizeInspector.HelpURL_ReleaseNotes);
            }

            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Tutorials", EditorStyles.miniLabel))
            {
                Application.OpenURL(HelpURL_Tutorials);
            }

            GUILayout.Space(10);

            if (GUILayout.Button("Ask a Question", EditorStyles.miniLabel))
            {
                Application.OpenURL(HelpURL_forum);
            }

            GUILayout.Space(10);

            if (GUILayout.Button("Documentation", EditorStyles.miniLabel))
            {
                Application.OpenURL(HelpURL_Documentation);
            }
            GUILayout.EndHorizontal();
            EditorGUIUtility.labelWidth = 0;

            GUILayout.EndVertical();

            serializedObject.ApplyModifiedProperties();
        }
        void OnGUI_LanguageList()
        {
            GUILayout.BeginHorizontal(EditorStyles.toolbar);
            GUILayout.FlexibleSpace();
            GUILayout.Label("Languages:", EditorStyles.miniLabel, GUILayout.ExpandWidth(false));
            GUILayout.FlexibleSpace();
            GUILayout.Label("Code:", EditorStyles.miniLabel);
            GUILayout.Space(170);
            GUILayout.EndHorizontal();

            //--[ Language List ]--------------------------

            int IndexLanguageToDelete = -1;
            int LanguageToMoveUp      = -1;
            int LanguageToMoveDown    = -1;

            mScrollPos_Languages = GUILayout.BeginScrollView(mScrollPos_Languages, EditorStyles.textArea, GUILayout.MinHeight(100), GUILayout.MaxHeight(Screen.height), GUILayout.ExpandHeight(false));

            if (mLanguageCodePopupList == null || mLanguageCodePopupList.Count == 0)
            {
                mLanguageCodePopupList = GoogleLanguages.GetLanguagesForDropdown("", "");
                mLanguageCodePopupList.Sort();
                mLanguageCodePopupList.Insert(0, string.Empty);
            }

            for (int i = 0, imax = mProp_Languages.arraySize; i < imax; ++i)
            {
                SerializedProperty Prop_Lang     = mProp_Languages.GetArrayElementAtIndex(i);
                SerializedProperty Prop_LangName = Prop_Lang.FindPropertyRelative("Name");
                SerializedProperty Prop_LangCode = Prop_Lang.FindPropertyRelative("Code");
                SerializedProperty Prop_Flags    = Prop_Lang.FindPropertyRelative("Flags");
                bool isLanguageEnabled           = (Prop_Flags.intValue & (int)eLanguageDataFlags.DISABLED) == 0;

                GUI.color = isLanguageEnabled ? Color.white : new Color(1, 1, 1, 0.3f);
                GUILayout.BeginHorizontal();

                if (GUILayout.Button("X", "toolbarbutton", GUILayout.ExpandWidth(false)))
                {
                    IndexLanguageToDelete = i;
                }

                GUILayout.BeginHorizontal(EditorStyles.toolbar);

                EditorGUI.BeginChangeCheck();
                string LanName = EditorGUILayout.TextField(Prop_LangName.stringValue, GUILayout.ExpandWidth(true));
                if (EditorGUI.EndChangeCheck() && !string.IsNullOrEmpty(LanName))
                {
                    Prop_LangName.stringValue = LanName;
                }

                var currentCode = "[" + Prop_LangCode.stringValue + "]";

                if (isLanguageEnabled)
                {
                    int Index = Mathf.Max(0, mLanguageCodePopupList.FindIndex(c => c.Contains(currentCode)));
                    EditorGUI.BeginChangeCheck();
                    Index = EditorGUILayout.Popup(Index, mLanguageCodePopupList.ToArray(), EditorStyles.toolbarPopup, GUILayout.Width(60));
                    if (EditorGUI.EndChangeCheck() && Index >= 0)
                    {
                        currentCode = mLanguageCodePopupList[Index];
                        int i0 = currentCode.IndexOf("[");
                        int i1 = currentCode.IndexOf("]");
                        if (i0 >= 0 && i1 > i0)
                        {
                            Prop_LangCode.stringValue = currentCode.Substring(i0 + 1, i1 - i0 - 1);
                        }
                        else
                        {
                            Prop_LangCode.stringValue = string.Empty;
                        }
                    }
                    var rect = GUILayoutUtility.GetLastRect();
                    GUI.Label(rect, Prop_LangCode.stringValue, EditorStyles.toolbarPopup);
                }
                else
                {
                    GUILayout.Label(Prop_LangCode.stringValue, EditorStyles.toolbarPopup, GUILayout.Width(60));
                }

                GUILayout.EndHorizontal();

                GUI.enabled = (i < imax - 1);
                if (GUILayout.Button("\u25BC", EditorStyles.toolbarButton, GUILayout.Width(18)))
                {
                    LanguageToMoveDown = i;
                }
                GUI.enabled = i > 0;
                if (GUILayout.Button("\u25B2", EditorStyles.toolbarButton, GUILayout.Width(18)))
                {
                    LanguageToMoveUp = i;
                }

                GUI.enabled = true;
                if (GUILayout.Button(new GUIContent("Show", "Preview all localizations into this language"), EditorStyles.toolbarButton, GUILayout.Width(35)))
                {
                    LocalizationManager.SetLanguageAndCode(LanName, Prop_LangCode.stringValue, false, true);
                }

                if (GUILayout.Button(new GUIContent("Translate", "Translate all empty terms"), EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
                {
                    TranslateAllToLanguage(LanName);
                }
                GUI.enabled = true;
                GUI.color   = Color.white;

                EditorGUI.BeginChangeCheck();
                isLanguageEnabled = EditorGUILayout.Toggle(isLanguageEnabled, GUILayout.Width(15));
                if (EditorGUI.EndChangeCheck())
                {
                    Prop_Flags.intValue = (Prop_Flags.intValue & ~(int)eLanguageDataFlags.DISABLED) | (isLanguageEnabled ? 0 : (int)eLanguageDataFlags.DISABLED);
                }

                GUILayout.EndHorizontal();
            }

            GUILayout.EndScrollView();

            OnGUI_AddLanguage(mProp_Languages);

            if (mConnection_WWW != null || mConnection_Text.Contains("Translating"))
            {
                // Connection Status Bar
                int    time    = (int)((Time.realtimeSinceStartup % 2) * 2.5);
                string Loading = mConnection_Text + ".....".Substring(0, time);
                GUI.color = Color.gray;
                GUILayout.BeginHorizontal(EditorStyles.textArea);
                GUILayout.Label(Loading, EditorStyles.miniLabel);
                GUI.color = Color.white;
                if (GUILayout.Button("Cancel", EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
                {
                    EditorApplication.update -= DelayedStartTranslation;
                    StopConnectionWWW();
                }
                GUILayout.EndHorizontal();
                Repaint();
            }

            if (IndexLanguageToDelete >= 0)
            {
                mLanguageSource.RemoveLanguage(mLanguageSource.mLanguages[IndexLanguageToDelete].Name);
                serializedObject.Update();
                ParseTerms(true, false);
            }

            if (LanguageToMoveUp >= 0)
            {
                SwapLanguages(LanguageToMoveUp, LanguageToMoveUp - 1);
            }
            if (LanguageToMoveDown >= 0)
            {
                SwapLanguages(LanguageToMoveDown, LanguageToMoveDown + 1);
            }
        }
        public override void OnInspectorGUI()
        {
            Undo.RecordObject(target, "Localize");

            GUI.backgroundColor = Color.Lerp(Color.black, Color.gray, 1);
            GUILayout.BeginVertical(GUIStyle_Background, GUILayout.Height(1));
            GUI.backgroundColor = Color.white;

            if (GUILayout.Button("Localize", GUIStyle_Header))
            {
                //Application.OpenURL(HelpURL_Documentation);
            }
            GUILayout.Space(-10);

            LocalizationManager.UpdateSources();

            if (LocalizationManager.Sources.Count == 0)
            {
                EditorGUILayout.HelpBox("Unable to find a Language Source.", MessageType.Warning);
            }
            else
            {
                GUILayout.Space(10);
                OnGUI_Target();
                GUILayout.Space(10);
                OnGUI_Terms();

                //if (mGUI_ShowTems || mGUI_ShowReferences) GUILayout.Space(5);

                OnGUI_References();

                if (mLocalize.mGUI_ShowReferences || mLocalize.mGUI_ShowCallback)
                {
                    GUILayout.Space(10);
                }

                //Localize loc = target as Localize;

                //--[ Localize Callback ]----------------------
                EditorGUILayout.PropertyField(mProp_CallbackEvent, new GUIContent("On Localize Callback"));

                //string HeaderTitle = "On Localize Call:";
                //if (!mLocalize.mGUI_ShowCallback && loc.LocalizeCallBack.Target!=null && !string.IsNullOrEmpty(loc.LocalizeCallBack.MethodName))
                //	HeaderTitle = string.Concat(HeaderTitle, " <b>",loc.LocalizeCallBack.Target.name, ".</b><i>", loc.LocalizeCallBack.MethodName, "</i>");
                //mLocalize.mGUI_ShowCallback = GUITools.DrawHeader(HeaderTitle, mLocalize.mGUI_ShowCallback);
                //if (mLocalize.mGUI_ShowCallback)
                //{
                //	GUITools.BeginContents();
                //		DrawEventCallBack( loc.LocalizeCallBack, loc );
                //	GUITools.EndContents();
                //}
            }
            OnGUI_Source();

            GUILayout.Space(10);

            GUITools.OnGUI_Footer("I2 Localization", LocalizationManager.GetVersion(), HelpURL_forum, HelpURL_Documentation, LocalizeInspector.HelpURL_AssetStore);

            GUILayout.EndVertical();

            serializedObject.ApplyModifiedProperties();
            if (Event.current.type == EventType.Repaint)
            {
                LocalizationEditor.mTestAction     = LocalizationEditor.eTest_ActionType.None;
                LocalizationEditor.mTestActionArg  = null;
                LocalizationEditor.mTestActionArg2 = null;
            }
        }
        // this method shows the key description and the localization to each language
        public static TermData OnGUI_Keys_Languages(string Key, Localize localizeCmp, bool IsPrimaryKey = true)
        {
            if (Key == null)
            {
                Key = string.Empty;
            }

            TermData termdata = null;

            LanguageSourceData source = mLanguageSource;

            if (localizeCmp != null && localizeCmp.Source != null)
            {
                source = localizeCmp.Source.mSource;
            }

            if (source == null)
            {
                source = LocalizationManager.GetSourceContaining(Key, false);
            }

            if (source == null)
            {
                if (localizeCmp == null)
                {
                    source = LocalizationManager.Sources[0];
                }
                else
                {
                    source = LocalizationManager.GetSourceContaining(IsPrimaryKey ? localizeCmp.SecondaryTerm : localizeCmp.Term, true);
                }
            }


            if (string.IsNullOrEmpty(Key))
            {
                EditorGUILayout.HelpBox("Select a Term to Localize", MessageType.Info);
                return(null);
            }
            else
            {
                termdata = source.GetTermData(Key);
                if (termdata == null && localizeCmp != null)
                {
                    var realSource = LocalizationManager.GetSourceContaining(Key, false);
                    if (realSource != null)
                    {
                        termdata = realSource.GetTermData(Key);
                        source   = realSource;
                    }
                }
                if (termdata == null)
                {
                    if (Key == "-")
                    {
                        return(null);
                    }
                    EditorGUILayout.HelpBox(string.Format("Key '{0}' is not Localized or it is in a different Language Source", Key), MessageType.Error);
                    GUILayout.BeginHorizontal();
                    GUILayout.FlexibleSpace();
                    if (GUILayout.Button("Add Term to Source"))
                    {
                        var termType = eTermType.Text;
                        if (localizeCmp != null && localizeCmp.mLocalizeTarget != null)
                        {
                            termType = IsPrimaryKey ? localizeCmp.mLocalizeTarget.GetPrimaryTermType(localizeCmp)
                                                    : localizeCmp.mLocalizeTarget.GetSecondaryTermType(localizeCmp);
                        }

                        AddTerm(Key, true, termType);
                    }
                    GUILayout.FlexibleSpace();
                    GUILayout.EndHorizontal();

                    return(null);
                }
            }

            //--[ Type ]----------------------------------
            if (localizeCmp == null)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Type:", GUILayout.ExpandWidth(false));
                eTermType NewType = (eTermType)EditorGUILayout.EnumPopup(termdata.TermType, GUILayout.ExpandWidth(true));
                if (termdata.TermType != NewType)
                {
                    termdata.TermType = NewType;
                }
                GUILayout.EndHorizontal();
            }


            //--[ Description ]---------------------------

            mKeysDesc_AllowEdit = GUILayout.Toggle(mKeysDesc_AllowEdit, "Description", EditorStyles.foldout, GUILayout.ExpandWidth(true));

            if (mKeysDesc_AllowEdit)
            {
                string NewDesc = EditorGUILayout.TextArea(termdata.Description, Style_WrapTextField);
                if (NewDesc != termdata.Description)
                {
                    termdata.Description = NewDesc;
                    EditorUtility.SetDirty(source.owner);
                }
            }
            else
            {
                EditorGUILayout.HelpBox(string.IsNullOrEmpty(termdata.Description) ? "No description" : termdata.Description, MessageType.Info);
            }

            OnGUI_Keys_Language_SpecializationsBar(termdata);

            OnGUI_Keys_Languages(Key, ref termdata, localizeCmp, IsPrimaryKey, source);
            return(termdata);
        }
        static void OnGUI_Keys_LanguageTranslations(string Key, Localize localizeCmp, bool IsPrimaryKey, ref TermData termdata, LanguageSourceData source)
        {
            bool IsSelect = Event.current.type == EventType.MouseUp;

            for (int i = 0; i < source.mLanguages.Count; ++i)
            {
                bool forcePreview      = false;
                bool isEnabledLanguage = source.mLanguages[i].IsEnabled();

                if (!isEnabledLanguage)
                {
                    if (!GUI_ShowDisabledLanguagesTranslation)
                    {
                        continue;
                    }
                    GUI.color = new Color(GUI.color.r, GUI.color.g, GUI.color.b, 0.35f);
                }
                GUILayout.BeginHorizontal();

                if (GUILayout.Button(source.mLanguages[i].Name, EditorStyles.label, GUILayout.Width(100)))
                {
                    forcePreview = true;
                }


                string Translation = termdata.GetTranslation(i, GUI_SelectedSpecialization, editMode: true);
                if (Translation == null)
                {
                    Translation = string.Empty;
                }

//				if (termdata.Languages[i] != termdata.Languages_Touch[i] && !string.IsNullOrEmpty(termdata.Languages[i]) && !string.IsNullOrEmpty(termdata.Languages_Touch[i]))
//					GUI.contentColor = GUITools.LightYellow;

                if (termdata.TermType == eTermType.Text || termdata.TermType == eTermType.Child)
                {
                    EditorGUI.BeginChangeCheck();
                    string CtrName = "TranslatedText" + i;
                    GUI.SetNextControlName(CtrName);

                    EditPluralTranslations(ref Translation, i, source.mLanguages[i].Code);
                    //Translation = EditorGUILayout.TextArea(Translation, Style_WrapTextField, GUILayout.Width(Screen.width - 260 - (autoTranslated ? 20 : 0)));
                    if (EditorGUI.EndChangeCheck())
                    {
                        termdata.SetTranslation(i, Translation, GUI_SelectedSpecialization);
                        EditorUtility.SetDirty(source.owner);
                        forcePreview = true;
                    }

                    if (localizeCmp != null &&
                        (forcePreview || /*GUI.changed || */ (GUI.GetNameOfFocusedControl() == CtrName && IsSelect)))
                    {
                        if (IsPrimaryKey && string.IsNullOrEmpty(localizeCmp.Term))
                        {
                            localizeCmp.mTerm = Key;
                        }

                        if (!IsPrimaryKey && string.IsNullOrEmpty(localizeCmp.SecondaryTerm))
                        {
                            localizeCmp.mTermSecondary = Key;
                        }

                        string PreviousLanguage = LocalizationManager.CurrentLanguage;
                        LocalizationManager.PreviewLanguage(source.mLanguages[i].Name);
                        if (forcePreview || IsSelect)
                        {
                            LocalizationManager.LocalizeAll();
                        }
                        else
                        {
                            localizeCmp.OnLocalize(true);
                        }
                        LocalizationManager.PreviewLanguage(PreviousLanguage);
                        EditorUtility.SetDirty(localizeCmp);
                    }
                    GUI.contentColor = Color.white;

                    //if (autoTranslated)
                    //{
                    //    if (GUILayout.Button(new GUIContent("\u2713"/*"A"*/,"Translated by Google Translator\nClick the button to approve the translation"), EditorStyles.toolbarButton, GUILayout.Width(autoTranslated ? 20 : 0)))
                    //    {
                    //        termdata.Flags[i] &= (byte)(byte.MaxValue ^ (byte)(GUI_SelectedSpecialization==0 ? TranslationFlag.AutoTranslated_Normal : TranslationFlag.AutoTranslated_Touch));
                    //    }
                    //}

                    if (termdata.TermType == eTermType.Text)
                    {
                        if (TestButtonArg(eTest_ActionType.Button_Term_Translate, i, new GUIContent("T", "Translate"), EditorStyles.toolbarButton, GUILayout.Width(20)))
                        {
                            var termData = termdata;
                            var indx     = i;
                            var key      = Key;
                            GUITools.DelayedCall(() => TranslateTerm(key, termData, source, indx));
                            GUI.FocusControl(string.Empty);
                        }
                    }
                }
                else
                {
                    string MultiSpriteName = string.Empty;

                    if (termdata.TermType == eTermType.Sprite && Translation.EndsWith("]", StringComparison.Ordinal))                   // Handle sprites of type (Multiple):   "SpritePath[SpriteName]"
                    {
                        int idx = Translation.LastIndexOf("[", StringComparison.Ordinal);
                        int len = Translation.Length - idx - 2;
                        MultiSpriteName = Translation.Substring(idx + 1, len);
                        Translation     = Translation.Substring(0, idx);
                    }

                    Object Obj = null;

                    // Try getting the asset from the References section
                    if (localizeCmp != null)
                    {
                        Obj = localizeCmp.FindTranslatedObject <Object>(Translation);
                    }
                    if (Obj == null && source != null)
                    {
                        Obj = source.FindAsset(Translation);
                    }

                    // If it wasn't in the references, Load it from Resources
                    if (Obj == null && localizeCmp == null)
                    {
                        Obj = ResourceManager.pInstance.LoadFromResources <Object>(Translation);
                    }

                    Type ObjType = typeof(Object);
                    switch (termdata.TermType)
                    {
                    case eTermType.Font: ObjType = typeof(Font); break;

                    case eTermType.Texture: ObjType = typeof(Texture); break;

                    case eTermType.AudioClip: ObjType = typeof(AudioClip); break;

                    case eTermType.GameObject: ObjType = typeof(GameObject); break;

                    case eTermType.Sprite: ObjType = typeof(Sprite); break;

                    case eTermType.Material: ObjType = typeof(Material); break;

#if NGUI
                    case eTermType.UIAtlas: ObjType = typeof(UIAtlas); break;

                    case eTermType.UIFont: ObjType = typeof(UIFont); break;
#endif
#if TK2D
                    case eTermType.TK2dFont: ObjType = typeof(tk2dFont); break;

                    case eTermType.TK2dCollection: ObjType = typeof(tk2dSpriteCollection); break;
#endif

#if TextMeshPro
                    case eTermType.TextMeshPFont: ObjType = typeof(TMPro.TMP_FontAsset); break;
#endif

#if SVG
                    case eTermType.SVGAsset: ObjType = typeof(SVGImporter.SVGAsset); break;
#endif

                    case eTermType.Object: ObjType = typeof(Object); break;
                    }

                    if (Obj != null && !string.IsNullOrEmpty(MultiSpriteName))
                    {
                        string   sPath = AssetDatabase.GetAssetPath(Obj);
                        Object[] objs  = AssetDatabase.LoadAllAssetRepresentationsAtPath(sPath);
                        Obj = null;
                        for (int j = 0, jmax = objs.Length; j < jmax; ++j)
                        {
                            if (objs[j].name.Equals(MultiSpriteName))
                            {
                                Obj = objs[j];
                                break;
                            }
                        }
                    }

                    bool bShowTranslationLabel = (Obj == null && !string.IsNullOrEmpty(Translation));
                    if (bShowTranslationLabel)
                    {
                        GUI.backgroundColor = GUITools.DarkGray;
                        GUILayout.BeginVertical(EditorStyles.textArea, GUILayout.Height(1));
                        GUILayout.Space(2);

                        GUI.backgroundColor = Color.white;
                    }

                    Object NewObj = EditorGUILayout.ObjectField(Obj, ObjType, true, GUILayout.ExpandWidth(true));
                    if (Obj != NewObj)
                    {
                        string sPath = null;
                        if (NewObj != null)
                        {
                            sPath = AssetDatabase.GetAssetPath(NewObj);

                            mCurrentInspector.serializedObject.ApplyModifiedProperties();
                            foreach (var cmp in mCurrentInspector.serializedObject.targetObjects)
                            {
                                AddObjectPath(ref sPath, cmp as Localize, NewObj);
                            }
                            mCurrentInspector.serializedObject.ApplyModifiedProperties();

                            if (HasObjectInReferences(NewObj, localizeCmp))
                            {
                                sPath = NewObj.name;
                            }
                            else
                            if (termdata.TermType == eTermType.Sprite)
                            {
                                sPath += "[" + NewObj.name + "]";
                            }
                        }

                        termdata.SetTranslation(i, sPath, GUI_SelectedSpecialization);
                        EditorUtility.SetDirty(source.owner);
                    }

                    if (bShowTranslationLabel)
                    {
                        GUILayout.BeginHorizontal();
                        GUI.color = Color.red;
                        GUILayout.FlexibleSpace();
                        GUILayout.Label(Translation, EditorStyles.miniLabel);
                        GUILayout.FlexibleSpace();
                        GUI.color = Color.white;
                        GUILayout.EndHorizontal();
                        GUILayout.EndVertical();
                    }
                }

                GUILayout.EndHorizontal();
                GUI.color = Color.white;
            }
        }
        bool EditTerms()
        {
            var changed = false;

            if (mTarget.PrimaryTerm == null)
            {
                return(false);
            }

            // make sure our FsmString is not pointing to a variable.
            mTarget.PrimaryTerm.UseVariable   = false;
            mTarget.SecondaryTerm.UseVariable = false;

            var go = mTarget.Fsm.GetOwnerDefaultTarget(mTarget.GameObject);

            if (go != null)
            {
                mLocalize = go.GetComponent <Localize> ();
            }

            var terms = (mLocalize != null && mLocalize.Source != null) ? mLocalize.Source.GetTermsList() : LocalizationManager.GetTermsList();

            terms.Sort(System.StringComparer.OrdinalIgnoreCase);
            terms.Add("");
            terms.Add("<inferred from text>");
            terms.Add("<none>");
            var aTerms = terms.ToArray();

            changed |= DoTermPopup("Primary Term", mTarget.PrimaryTerm, aTerms);
            changed |= DoTermPopup("Secondary Term", mTarget.SecondaryTerm, aTerms);

            return(GUI.changed || changed);
        }
Example #13
0
        void OnGUI_Source()
        {
            GUILayout.BeginHorizontal();

            LanguageSource currentSource = mLocalize.Source;

            if (currentSource == null)
            {
                currentSource = LocalizationManager.GetSourceContaining(mLocalize.Term);
            }

            if (GUILayout.Button("Open Source", EditorStyles.toolbarButton, GUILayout.Width(100)))
            {
                Selection.activeObject = currentSource;

                string sTerm, sSecondary;
                mLocalize.GetFinalTerms(out sTerm, out sSecondary);
                if (GUI_SelectedTerm == 1)
                {
                    sTerm = sSecondary;
                }
                LocalizationEditor.mKeyToExplore = sTerm;
            }

            GUILayout.Space(2);

            GUILayout.BeginHorizontal(EditorStyles.toolbar);
            EditorGUI.BeginChangeCheck();
            if (!mLocalize.Source)
            {
                GUI.contentColor = Color.Lerp(Color.gray, Color.yellow, 0.1f);
            }
            LanguageSource NewSource = EditorGUILayout.ObjectField(currentSource, typeof(LanguageSource), true) as LanguageSource;

            GUI.contentColor = Color.white;
            if (EditorGUI.EndChangeCheck())
            {
                mLocalize.Source = NewSource;
                string sTerm, sSecondary;
                mLocalize.GetFinalTerms(out sTerm, out sSecondary);
                if (GUI_SelectedTerm == 1)
                {
                    sTerm = sSecondary;
                }
                UpdateTermsList(sTerm);
            }

            if (GUILayout.Button(new GUIContent("Detect", "Finds the LanguageSource containing the selected term, the term list will now only show terms inside that source."), EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
            {
                string sTerm, sSecondary;
                mLocalize.GetFinalTerms(out sTerm, out sSecondary);
                if (GUI_SelectedTerm == 1)
                {
                    sTerm = sSecondary;
                }

                mLocalize.Source = LocalizationManager.GetSourceContaining(sTerm, false);
                mTermsArray      = null;
            }
            GUILayout.EndHorizontal();

            GUILayout.EndHorizontal();
        }
        public static void ChangeXcodePlist(BuildTarget buildTarget, string pathToBuiltProject)
        {
            if (buildTarget != BuildTarget.iOS)
            {
                return;
            }

            if (LocalizationManager.Sources.Count <= 0)
            {
                LocalizationManager.UpdateSources();
            }
            var langCodes = LocalizationManager.GetAllLanguagesCode(false).Concat(LocalizationManager.GetAllLanguagesCode(true)).Distinct().ToList();

            if (langCodes.Count <= 0)
            {
                return;
            }

            try
            {
                //----[ Export localized languages to the info.plist ]---------

                string        plistPath = pathToBuiltProject + "/Info.plist";
                PlistDocument plist     = new PlistDocument();
                plist.ReadFromString(File.ReadAllText(plistPath));

                PlistElementDict rootDict = plist.root;

                // Get Language root
                var langArray = rootDict.CreateArray("CFBundleLocalizations");

                // Set the Language Codes
                foreach (var code in langCodes)
                {
                    if (code == null || code.Length < 2)
                    {
                        continue;
                    }
                    langArray.AddString(code);
                }

                rootDict.SetString("CFBundleDevelopmentRegion", langCodes[0]);

                // Write to file
                File.WriteAllText(plistPath, plist.WriteToString());

                //--[ Localize App Name ]----------

                string LocalizationRoot = pathToBuiltProject + "/I2Localization";
                if (!Directory.Exists(LocalizationRoot))
                {
                    Directory.CreateDirectory(LocalizationRoot);
                }

                var    project  = new PBXProject();
                string projPath = PBXProject.GetPBXProjectPath(pathToBuiltProject);
                //if (!projPath.EndsWith("xcodeproj"))
                //projPath = projPath.Substring(0, projPath.LastIndexOfAny("/\\".ToCharArray()));

                project.ReadFromFile(projPath);
                //var targetName = PBXProject.GetUnityTargetName();
                //string projBuild = project.TargetGuidByName( targetName );

                project.RemoveLocalizationVariantGroup("I2 Localization");
                // Set the Language Overrides
                foreach (var code in langCodes)
                {
                    if (code == null || code.Length < 2)
                    {
                        continue;
                    }

                    var LanguageDirRoot = LocalizationRoot + "/" + code + ".lproj";
                    if (!Directory.Exists(LanguageDirRoot))
                    {
                        Directory.CreateDirectory(LanguageDirRoot);
                    }

                    var infoPlistPath = LanguageDirRoot + "/InfoPlist.strings";
                    var InfoPlist     = string.Format("CFBundleDisplayName = \"{0}\";", LocalizationManager.GetAppName(code));
                    File.WriteAllText(infoPlistPath, InfoPlist);

                    var langProjectRoot = "I2Localization/" + code + ".lproj";

                    var stringPaths = LanguageDirRoot + "/Localizable.strings";
                    File.WriteAllText(stringPaths, string.Empty);

                    project.AddLocalization(langProjectRoot + "/Localizable.strings", langProjectRoot + "/Localizable.strings", "I2 Localization");
                    project.AddLocalization(langProjectRoot + "/InfoPlist.strings", langProjectRoot + "/InfoPlist.strings", "I2 Localization");
                }

                project.WriteToFile(projPath);
            }
            catch (System.Exception e)
            {
                Debug.Log(e);
            }
        }
Example #15
0
        // this method shows the key description and the localization to each language
        public static void OnGUI_Keys_Languages(string Key, Localize localizeCmp, bool IsPrimaryKey = true)
        {
            if (Key == null)
            {
                Key = string.Empty;
            }

            TermData termdata = null;

            LanguageSource source = (localizeCmp == null ? mLanguageSource : localizeCmp.Source);

            if (source == null)
            {
                source = LocalizationManager.GetSourceContaining(Key, false);
            }

            if (source == null)
            {
                if (localizeCmp == null)
                {
                    source = LocalizationManager.Sources[0];
                }
                else
                {
                    source = LocalizationManager.GetSourceContaining(IsPrimaryKey ? localizeCmp.SecondaryTerm : localizeCmp.Term, true);
                }
            }


            if (string.IsNullOrEmpty(Key))
            {
                EditorGUILayout.HelpBox("Select a Term to Localize", UnityEditor.MessageType.Info);
                return;
            }
            else
            {
                termdata = source.GetTermData(Key);
                if (termdata == null && localizeCmp != null)
                {
                    var realSource = LocalizationManager.GetSourceContaining(Key, false);
                    if (realSource != null)
                    {
                        termdata = realSource.GetTermData(Key);
                        source   = realSource;
                    }
                }
                if (termdata == null)
                {
                    if (Key == "-")
                    {
                        return;
                    }
                    EditorGUILayout.HelpBox(string.Format("Key '{0}' is not Localized or it is in a different Language Source", Key), UnityEditor.MessageType.Error);
                    GUILayout.BeginHorizontal();
                    GUILayout.FlexibleSpace();
                    if (GUILayout.Button("Add Term to Source"))
                    {
                        source.AddTerm(Key, eTermType.Text);
                        AddParsedTerm(Key, null, null, 1);
                        SetAllTerms_When_InferredTerms_IsInSource();
                    }
                    GUILayout.FlexibleSpace();
                    GUILayout.EndHorizontal();

                    return;
                }
            }

            //--[ Type ]----------------------------------
            if (localizeCmp == null)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Type:", GUILayout.ExpandWidth(false));
                eTermType NewType = (eTermType)EditorGUILayout.EnumPopup(termdata.TermType, GUILayout.ExpandWidth(true));
                if (termdata.TermType != NewType)
                {
                    termdata.TermType = NewType;
                }
                GUILayout.EndHorizontal();
            }


            //--[ Description ]---------------------------

            mKeysDesc_AllowEdit = GUILayout.Toggle(mKeysDesc_AllowEdit, "Description", EditorStyles.foldout, GUILayout.ExpandWidth(true));

            if (mKeysDesc_AllowEdit)
            {
                string NewDesc = EditorGUILayout.TextArea(termdata.Description, LocalizationEditor.Style_WrapTextField);
                if (NewDesc != termdata.Description)
                {
                    termdata.Description = NewDesc;
                    EditorUtility.SetDirty(source);
                }
            }
            else
            {
                EditorGUILayout.HelpBox(string.IsNullOrEmpty(termdata.Description) ? "No description" : termdata.Description, UnityEditor.MessageType.Info);
            }

            OnGUI_Keys_Language_SpecializationsBar();

            //--[ Languages ]---------------------------
            GUILayout.BeginVertical("AS TextArea", GUILayout.Height(1));

            OnGUI_Keys_LanguageTranslations(Key, localizeCmp, IsPrimaryKey, ref termdata, source);

            if (termdata.TermType == eTermType.Text)
            {
                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("Translate All", GUILayout.Width(85)))
                {
                    string mainText = localizeCmp == null?LanguageSource.GetKeyFromFullTerm(Key) : localizeCmp.GetMainTargetsText();

                    for (int i = 0; i < source.mLanguages.Count; ++i)
                    {
                        if (string.IsNullOrEmpty(termdata.Languages[i]) && source.mLanguages[i].IsEnabled())
                        {
                            if (GUI_SelectedInputType == 0)
                            {
                                Translate(mainText, ref termdata, ref termdata.Languages[i], source.mLanguages[i].Code);
                                //termdata.Flags[i] |= (byte)TranslationFlag.AutoTranslated_Normal;
                            }
                            else
                            {
                                Translate(mainText, ref termdata, ref termdata.Languages_Touch[i], source.mLanguages[i].Code);
                                //termdata.Flags[i] |= (byte)TranslationFlag.AutoTranslated_Touch;
                            }
                        }
                    }
                    GUI.FocusControl(string.Empty);
                }
                GUILayout.EndHorizontal();
            }
            GUILayout.EndVertical();
        }
 void RemoveUnusedReferences(Localize cmp)
 {
     cmp.TranslatedObjects.RemoveAll(x => !IsUsingReference(LocalizationManager.GetTermData(cmp.Term), x) && !IsUsingReference(LocalizationManager.GetTermData(cmp.SecondaryTerm), x));
     if (cmp.TranslatedObjects.Count != cmp.mAssetDictionary.Count)
     {
         cmp.UpdateAssetDictionary();
     }
 }
Example #17
0
        static void OnGUI_Keys_LanguageTranslations(string Key, Localize localizeCmp, bool IsPrimaryKey, ref TermData termdata, LanguageSource source)
        {
            bool IsSelect = Event.current.type == EventType.MouseUp;

            for (int i = 0; i < source.mLanguages.Count; ++i)
            {
                bool forcePreview      = false;
                bool isEnabledLanguage = source.mLanguages[i].IsEnabled();

                if (!isEnabledLanguage)
                {
                    if (!GUI_ShowDisabledLanguagesTranslation)
                    {
                        continue;
                    }
                    GUI.color = new Color(GUI.color.r, GUI.color.g, GUI.color.b, 0.35f);
                }
                GUILayout.BeginHorizontal();

                if (GUILayout.Button(source.mLanguages[i].Name, EditorStyles.label, GUILayout.Width(100)))
                {
                    forcePreview = true;
                }


                string Translation = (GUI_SelectedInputType == 0 ? termdata.Languages[i] : termdata.Languages_Touch[i]) ?? string.Empty;
                if (string.IsNullOrEmpty(Translation))
                {
                    Translation = (GUI_SelectedInputType == 1 ? termdata.Languages[i] : termdata.Languages_Touch[i]) ?? string.Empty;
                }

                if (termdata.Languages[i] != termdata.Languages_Touch[i] && !string.IsNullOrEmpty(termdata.Languages[i]) && !string.IsNullOrEmpty(termdata.Languages_Touch[i]))
                {
                    GUI.contentColor = GUITools.LightYellow;
                }

                if (termdata.TermType == eTermType.Text)
                {
                    GUI.changed = false;
                    string CtrName = "TranslatedText" + i;
                    GUI.SetNextControlName(CtrName);

                    bool autoTranslated = false;// termdata.IsAutoTranslated(i, GUI_SelectedInputType == 1);

                    Translation = EditorGUILayout.TextArea(Translation, LocalizationEditor.Style_WrapTextField, GUILayout.Width(Screen.width - 260 - (autoTranslated ? 20 : 0)));
                    if (GUI.changed)
                    {
                        if (GUI_SelectedInputType == 0)
                        {
                            termdata.Languages[i] = Translation;
                            //termdata.Flags[i] &= byte.MaxValue ^ (byte)TranslationFlag.AutoTranslated_Normal;
                        }
                        else
                        {
                            termdata.Languages_Touch[i] = Translation;
                            //termdata.Flags[i] &= byte.MaxValue ^ (byte)TranslationFlag.AutoTranslated_Touch;
                        }
                        EditorUtility.SetDirty(source);
                    }

                    if (localizeCmp != null &&
                        (forcePreview || GUI.changed || (GUI.GetNameOfFocusedControl() == CtrName && IsSelect)))
                    {
                        if (IsPrimaryKey && string.IsNullOrEmpty(localizeCmp.Term))
                        {
                            localizeCmp.mTerm = Key;
                        }

                        if (!IsPrimaryKey && string.IsNullOrEmpty(localizeCmp.SecondaryTerm))
                        {
                            localizeCmp.mTermSecondary = Key;
                        }

                        string PreviousLanguage = LocalizationManager.CurrentLanguage;
                        LocalizationManager.PreviewLanguage(source.mLanguages[i].Name);
                        if (forcePreview || IsSelect)
                        {
                            LocalizationManager.LocalizeAll();
                        }
                        else
                        {
                            localizeCmp.OnLocalize(true);
                        }
                        LocalizationManager.PreviewLanguage(PreviousLanguage);
                        EditorUtility.SetDirty(localizeCmp);
                    }
                    GUI.contentColor = Color.white;

                    //if (autoTranslated)
                    //{
                    //    if (GUILayout.Button(new GUIContent("\u2713"/*"A"*/,"Translated by Google Translator\nClick the button to approve the translation"), EditorStyles.toolbarButton, GUILayout.Width(autoTranslated ? 20 : 0)))
                    //    {
                    //        termdata.Flags[i] &= (byte)(byte.MaxValue ^ (byte)(GUI_SelectedInputType==0 ? TranslationFlag.AutoTranslated_Normal : TranslationFlag.AutoTranslated_Touch));
                    //    }
                    //}

                    if (GUILayout.Button("Translate", EditorStyles.toolbarButton, GUILayout.Width(80)))
                    {
                        string mainText = localizeCmp == null?LanguageSource.GetKeyFromFullTerm(Key) : localizeCmp.GetMainTargetsText();

                        if (GUI_SelectedInputType == 0)
                        {
                            Translate(mainText, ref termdata, ref termdata.Languages[i], source.mLanguages[i].Code);
                            //termdata.Flags[i] |= (byte)TranslationFlag.AutoTranslated_Normal;
                        }
                        else
                        {
                            Translate(mainText, ref termdata, ref termdata.Languages_Touch[i], source.mLanguages[i].Code);
                            //termdata.Flags[i] |= (byte)TranslationFlag.AutoTranslated_Touch;
                        }
                        GUI.FocusControl(string.Empty);
                    }
                }
                else
                {
                    string MultiSpriteName = string.Empty;

                    if (termdata.TermType == eTermType.Sprite && Translation.EndsWith("]"))                     // Handle sprites of type (Multiple):   "SpritePath[SpriteName]"
                    {
                        int idx = Translation.LastIndexOf("[");
                        int len = Translation.Length - idx - 2;
                        MultiSpriteName = Translation.Substring(idx + 1, len);
                        Translation     = Translation.Substring(0, idx);
                    }

                    Object Obj = null;

                    // Try getting the asset from the References section
                    if (localizeCmp != null)
                    {
                        Obj = localizeCmp.FindTranslatedObject <Object>(Translation);
                    }
                    if (Obj == null && source != null)
                    {
                        Obj = source.FindAsset(Translation);
                    }

                    // If it wasn't in the references, Load it from Resources
                    if (Obj == null && localizeCmp == null)
                    {
                        Obj = ResourceManager.pInstance.LoadFromResources <Object>(Translation);
                    }

                    System.Type ObjType = typeof(Object);
                    switch (termdata.TermType)
                    {
                    case eTermType.Font: ObjType = typeof(Font); break;

                    case eTermType.Texture: ObjType = typeof(Texture); break;

                    case eTermType.AudioClip: ObjType = typeof(AudioClip); break;

                    case eTermType.GameObject: ObjType = typeof(GameObject); break;

                    case eTermType.Sprite: ObjType = typeof(Sprite); break;

                    case eTermType.Material: ObjType = typeof(Material); break;

#if NGUI
                    case eTermType.UIAtlas: ObjType = typeof(UIAtlas); break;

                    case eTermType.UIFont: ObjType = typeof(UIFont); break;
#endif
#if DFGUI
                    case eTermType.dfFont: ObjType = typeof(dfFont); break;

                    case eTermType.dfAtlas: ObjType = typeof(dfAtlas); break;
#endif

#if TK2D
                    case eTermType.TK2dFont: ObjType = typeof(tk2dFont); break;

                    case eTermType.TK2dCollection: ObjType = typeof(tk2dSpriteCollection); break;
#endif

#if TextMeshPro_Pre53
                    case eTermType.TextMeshPFont: ObjType = typeof(TMPro.TextMeshProFont); break;
#elif TextMeshPro
                    case eTermType.TextMeshPFont: ObjType = typeof(TMPro.TMP_FontAsset); break;
#endif

#if SVG
                    case eTermType.SVGAsset: ObjType = typeof(SVGImporter.SVGAsset); break;
#endif

                    case eTermType.Object: ObjType = typeof(Object); break;
                    }

                    if (Obj != null && !string.IsNullOrEmpty(MultiSpriteName))
                    {
                        string   sPath = AssetDatabase.GetAssetPath(Obj);
                        Object[] objs  = AssetDatabase.LoadAllAssetRepresentationsAtPath(sPath);
                        Obj = null;
                        for (int j = 0, jmax = objs.Length; j < jmax; ++j)
                        {
                            if (objs[j].name.Equals(MultiSpriteName))
                            {
                                Obj = objs[j];
                                break;
                            }
                        }
                    }

                    bool bShowTranslationLabel = (Obj == null && !string.IsNullOrEmpty(Translation));
                    if (bShowTranslationLabel)
                    {
                        GUI.backgroundColor = GUITools.DarkGray;
                        GUILayout.BeginVertical("AS TextArea", GUILayout.Height(1));
                        GUILayout.Space(2);

                        GUI.backgroundColor = Color.white;
                    }

                    Object NewObj = EditorGUILayout.ObjectField(Obj, ObjType, true, GUILayout.ExpandWidth(true));
                    if (Obj != NewObj && NewObj != null)
                    {
                        string sPath = AssetDatabase.GetAssetPath(NewObj);
                        AddObjectPath(ref sPath, localizeCmp, NewObj);
                        if (HasObjectInReferences(NewObj, localizeCmp))
                        {
                            sPath = NewObj.name;
                        }
                        else
                        if (termdata.TermType == eTermType.Sprite)
                        {
                            sPath += "[" + NewObj.name + "]";
                        }

                        if (GUI_SelectedInputType == 0)
                        {
                            termdata.Languages[i] = sPath;
                        }
                        else
                        {
                            termdata.Languages_Touch[i] = sPath;
                        }
                        EditorUtility.SetDirty(source);
                    }

                    if (bShowTranslationLabel)
                    {
                        GUILayout.BeginHorizontal();
                        GUI.color = Color.red;
                        GUILayout.FlexibleSpace();
                        GUILayout.Label(Translation, EditorStyles.miniLabel);
                        GUILayout.FlexibleSpace();
                        GUI.color = Color.white;
                        GUILayout.EndHorizontal();
                        GUILayout.EndVertical();
                    }
                }

                GUILayout.EndHorizontal();
                GUI.color = Color.white;
            }
        }
        void OnGUI_Source()
        {
            GUILayout.BeginHorizontal();

            ILanguageSource currentSource = mLocalize.Source;

            if (currentSource == null)
            {
                LanguageSourceData source = LocalizationManager.GetSourceContaining(mLocalize.Term);
                currentSource = source == null ? null : source.owner;
            }

            if (GUILayout.Button("Open Source", EditorStyles.toolbarButton, GUILayout.Width(100)))
            {
                Selection.activeObject = currentSource as UnityEngine.Object;

                string sTerm, sSecondary;
                mLocalize.GetFinalTerms(out sTerm, out sSecondary);
                if (GUI_SelectedTerm == 1)
                {
                    sTerm = sSecondary;
                }
                LocalizationEditor.mKeyToExplore = sTerm;
            }

            GUILayout.Space(2);

            GUILayout.BeginHorizontal(EditorStyles.toolbar);
            EditorGUI.BeginChangeCheck();
            if (mLocalize.Source == null)
            {
                GUI.contentColor = Color.Lerp(Color.gray, Color.yellow, 0.1f);
            }
            Object obj = EditorGUILayout.ObjectField(currentSource as Object, typeof(Object), true);

            GUI.contentColor = Color.white;
            if (EditorGUI.EndChangeCheck())
            {
                ILanguageSource NewSource = obj as ILanguageSource;
                if (NewSource == null && (obj as GameObject != null))
                {
                    NewSource = (obj as GameObject).GetComponent <LanguageSource>();
                }

                mLocalize.Source = NewSource;
                string sTerm, sSecondary;
                mLocalize.GetFinalTerms(out sTerm, out sSecondary);
                if (GUI_SelectedTerm == 1)
                {
                    sTerm = sSecondary;
                }
                UpdateTermsList(sTerm);
            }

            if (GUILayout.Button(new GUIContent("Detect", "Finds the LanguageSource containing the selected term, the term list will now only show terms inside that source."), EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
            {
                string sTerm, sSecondary;
                mLocalize.GetFinalTerms(out sTerm, out sSecondary);
                if (GUI_SelectedTerm == 1)
                {
                    sTerm = sSecondary;
                }

                var data = LocalizationManager.GetSourceContaining(sTerm, false);
                mLocalize.Source = data == null ? null : data.owner;
                mTermsArray      = null;
            }
            GUILayout.EndHorizontal();

            GUILayout.EndHorizontal();
        }
Example #19
0
        public string Import_Google_Result(string JsonString, eSpreadsheetUpdateMode UpdateMode, bool saveInPlayerPrefs = false)
        {
            try
            {
                string ErrorMsg = string.Empty;
                if (string.IsNullOrEmpty(JsonString) || JsonString == "\"\"")
                {
                    return(ErrorMsg);
                }

                int idxV  = JsonString.IndexOf("version=", StringComparison.Ordinal);
                int idxSV = JsonString.IndexOf("script_version=", StringComparison.Ordinal);
                if (idxV < 0 || idxSV < 0)
                {
                    return("Invalid Response from Google, Most likely the WebService needs to be updated");
                }

                idxV  += "version=".Length;
                idxSV += "script_version=".Length;

                string newSpreadsheetVersion = JsonString.Substring(idxV, JsonString.IndexOf(",", idxV, StringComparison.Ordinal) - idxV);
                var    scriptVersion         = int.Parse(JsonString.Substring(idxSV, JsonString.IndexOf(",", idxSV, StringComparison.Ordinal) - idxSV));

                if (newSpreadsheetVersion.Length > 19) // Check for corruption
                {
                    newSpreadsheetVersion = string.Empty;
                }

                if (scriptVersion != LocalizationManager.GetRequiredWebServiceVersion())
                {
                    return("The current Google WebService is not supported.\nPlease, delete the WebService from the Google Drive and Install the latest version.");
                }

                //Debug.Log (Google_LastUpdatedVersion + " - " + newSpreadsheetVersion);
                if (saveInPlayerPrefs && !IsNewerVersion(Google_LastUpdatedVersion, newSpreadsheetVersion))
#if UNITY_EDITOR
                { return(""); }
#else
                { return("LanguageSource is up-to-date"); }
#endif

                if (saveInPlayerPrefs)
                {
                    string PlayerPrefName = GetSourcePlayerPrefName();
                    PersistentStorage.Save("I2Source_" + PlayerPrefName, "[i2e]" + StringObfucator.Encode(JsonString));
                    PlayerPrefs.SetString("I2SourceVersion_" + PlayerPrefName, newSpreadsheetVersion);
                    PlayerPrefs.Save();
                }
                Google_LastUpdatedVersion = newSpreadsheetVersion;

                if (UpdateMode == eSpreadsheetUpdateMode.Replace)
                {
                    ClearAllData();
                }

                int CSVstartIdx = JsonString.IndexOf("[i2category]", StringComparison.Ordinal);
                while (CSVstartIdx > 0)
                {
                    CSVstartIdx += "[i2category]".Length;
                    int    endCat   = JsonString.IndexOf("[/i2category]", CSVstartIdx, StringComparison.Ordinal);
                    string category = JsonString.Substring(CSVstartIdx, endCat - CSVstartIdx);
                    endCat += "[/i2category]".Length;

                    int    endCSV = JsonString.IndexOf("[/i2csv]", endCat, StringComparison.Ordinal);
                    string csv    = JsonString.Substring(endCat, endCSV - endCat);

                    CSVstartIdx = JsonString.IndexOf("[i2category]", endCSV, StringComparison.Ordinal);

                    Import_I2CSV(category, csv, UpdateMode);

                    // Only the first CSV should clear the Data
                    if (UpdateMode == eSpreadsheetUpdateMode.Replace)
                    {
                        UpdateMode = eSpreadsheetUpdateMode.Merge;
                    }
                }

#if UNITY_EDITOR
                if (!string.IsNullOrEmpty(ErrorMsg))
                {
                    UnityEditor.EditorUtility.SetDirty(this);
                }
#endif
                return(ErrorMsg);
            }
            catch (System.Exception e)
            {
                Debug.LogWarning(e);
                return(e.ToString());
            }
        }
 public void Start()
 {
     LocalizationManager.EnableChangingCultureInfo(true);
 }
        bool OnGUI_SelectKey(ref string Term, bool Inherited)            // Inherited==true means that the mTerm is empty and we are using the Label.text instead
        {
            GUILayout.Space(5);
            GUILayout.BeginHorizontal();

            bool bChanged = false;

            mAllowEditKeyName = GUILayout.Toggle(mAllowEditKeyName, "Term:", EditorStyles.foldout, GUILayout.ExpandWidth(false));
            if (bChanged && mAllowEditKeyName)
            {
                mNewKeyName = Term;
            }

            bChanged = false;

            if (mTermsArray == null || System.Array.IndexOf(mTermsArray, Term) < 0)
            {
                UpdateTermsList(Term);
            }

            if (Inherited)
            {
                GUI.contentColor = Color.yellow * 0.8f;
            }

            int Index = System.Array.IndexOf(mTermsArray, Term);

            GUI.changed = false;

            int newIndex = EditorGUILayout.Popup(Index, mTermsArray);

            GUI.contentColor = Color.white;
            if (/*newIndex != Index && newIndex>=0*/ GUI.changed)
            {
                GUI.changed = false;
                mNewKeyName = Term = (newIndex == (mTermsArray.Length - 1)) ? string.Empty : mTermsArray[newIndex];
                if (GUI_SelectedTerm == 0)
                {
                    mLocalize.SetTerm(mNewKeyName);
                }
                else
                {
                    mLocalize.SetTerm(null, mNewKeyName);
                }
                mAllowEditKeyName = false;
                bChanged          = true;
            }
            LanguageSource source   = LocalizationManager.GetSourceContaining(Term);
            TermData       termData = source.GetTermData(Term);

            if (termData != null)
            {
                if (Inherited)
                {
                    bChanged = true;                     // if the term its inferred and a matching term its found, then use that
                }
                eTermType NewType = (eTermType)EditorGUILayout.EnumPopup(termData.TermType, GUILayout.Width(90));
                if (termData.TermType != NewType)
                {
                    termData.TermType = NewType;
                }
            }

            GUILayout.EndHorizontal();

            if (mAllowEditKeyName)
            {
                GUILayout.BeginHorizontal(GUILayout.Height(1));
                GUILayout.BeginHorizontal(EditorStyles.toolbar);
                if (mNewKeyName == null)
                {
                    mNewKeyName = string.Empty;
                }

                GUI.changed = false;
                mNewKeyName = EditorGUILayout.TextField(mNewKeyName, new GUIStyle("ToolbarSeachTextField"), GUILayout.ExpandWidth(true));
                if (GUI.changed)
                {
                    mTermsArray = null;                         // regenerate this array to apply filtering
                    GUI.changed = false;
                }

                if (GUILayout.Button(string.Empty, string.IsNullOrEmpty(mNewKeyName) ? "ToolbarSeachCancelButtonEmpty" : "ToolbarSeachCancelButton", GUILayout.ExpandWidth(false)))
                {
                    mTermsArray = null;                         // regenerate this array to apply filtering
                    mNewKeyName = string.Empty;
                }

                GUILayout.EndHorizontal();

                string ValidatedName = mNewKeyName;
                LanguageSource.ValidateFullTerm(ref ValidatedName);

                bool CanUseNewName = (source.GetTermData(ValidatedName) == null);
                GUI.enabled = (!string.IsNullOrEmpty(mNewKeyName) && CanUseNewName);
                if (GUILayout.Button("Create", EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
                {
                    mNewKeyName = ValidatedName;
                    Term        = mNewKeyName;
                    mTermsArray = null;                         // this recreates that terms array

                    LanguageSource Source = null;
                                        #if UNITY_EDITOR
                    if (mLocalize.Source != null)
                    {
                        Source = mLocalize.Source;
                    }
                                        #endif

                    if (Source == null)
                    {
                        Source = LocalizationManager.Sources[0];
                    }

                    Source.AddTerm(mNewKeyName, eTermType.Text);
                    mAllowEditKeyName          = false;
                    bChanged                   = true;
                    GUIUtility.keyboardControl = 0;
                }
                GUI.enabled = (termData != null && !string.IsNullOrEmpty(mNewKeyName) && CanUseNewName);
                if (GUILayout.Button(new GUIContent("Rename", "Renames the term in the source and updates every object using it in the current scene"), EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
                {
                    mNewKeyName       = ValidatedName;
                    Term              = mNewKeyName;
                    mTermsArray       = null;                 // this recreates that terms array
                    mAllowEditKeyName = false;
                    bChanged          = true;
                    LocalizationEditor.TermReplacements = new Dictionary <string, string>();
                    LocalizationEditor.TermReplacements[termData.Term] = mNewKeyName;
                    termData.Term = mNewKeyName;
                    source.UpdateDictionary(true);
                    LocalizationEditor.ReplaceTermsInCurrentScene();
                    GUIUtility.keyboardControl = 0;
                    EditorApplication.update  += LocalizationEditor.DoParseTermsInCurrentScene;
                }
                GUI.enabled = true;
                GUILayout.EndHorizontal();

                bChanged |= OnGUI_SelectKey_PreviewTerms(ref Term);
            }

            GUILayout.Space(5);
            return(bChanged);
        }
Example #22
0
 static void AutoRegister()
 {
     LocalizationManager.RegisterTarget(new LocalizeTarget_UnityStd_SpriteRenderer());
 }
 public static string Get(string Term, bool FixForRTL, int maxLineLengthForRTL)
 {
     return(LocalizationManager.GetTermTranslation(Term, FixForRTL, maxLineLengthForRTL, false));
 }
Example #24
0
        public override bool FindTarget(Localize cmp)
        {
            var termData = LocalizationManager.GetTermData(cmp.Term);

            return(termData != null && termData.TermType == eTermType.Child);
        }
 public static string Get(string Term)
 {
     return(LocalizationManager.GetTermTranslation(Term, LocalizationManager.IsRight2Left, 0, false));
 }
Example #26
0
 static void AutoRegister()
 {
     LocalizationManager.RegisterTarget(new LocalizeTarget_UnityStd_TextMesh());
 }
Example #27
0
        void OnGUI_Warning_SourceInScene()
        {
            if (mLanguageSource.UserAgreesToHaveItOnTheScene)
            {
                return;
            }

            LanguageSource source = (LanguageSource)target;

            if (LocalizationManager.IsGlobalSource(source.name) && !GUITools.ObjectExistInScene(source.gameObject))
            {
                return;
            }

            string Text = @"Its advised to only use the source in I2\Localization\Resources\I2Languages.prefab

That works as a GLOBAL source accessible in ALL scenes. That’s why its recommended to add all your translations there.

You don't need to instantiate that prefab into the scene, just click the prefab and add the Data.

Only use Sources in the scene when the localization is meant to be ONLY used there.
However, that's not advised and is only used in the Examples to keep them separated from your project localization.

Furthermore, having a source in the scene require that any Localize component get a reference to that source to work properly. By dragging the source into the field at the bottom of the Localize component.";

            EditorGUILayout.HelpBox(Text, MessageType.Warning);

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Keep as is"))
            {
                SerializedProperty Agree = serializedObject.FindProperty("UserAgreesToHaveItOnTheScene");
                Agree.boolValue = true;
            }

            GUILayout.FlexibleSpace();

            if (GUILayout.Button("Open the Global Source"))
            {
                GameObject Prefab = (Resources.Load(LocalizationManager.GlobalSources[0]) as GameObject);
                Selection.activeGameObject = Prefab;
            }

            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Delete this and open the Global Source"))
            {
                EditorApplication.CallbackFunction Callback = null;
                EditorApplication.update += Callback = () =>
                {
                    EditorApplication.update -= Callback;

                    if (source.GetComponents <Component>().Length <= 2)
                    {
                        Debug.Log("Deleting GameObject '" + source.name + "' and Openning the " + LocalizationManager.GlobalSources[0] + ".prefab");
                        DestroyImmediate(source.gameObject);
                    }
                    else
                    {
                        Debug.Log("Deleting the LanguageSource inside GameObject " + source.name + " and Openning the " + LocalizationManager.GlobalSources[0] + ".prefab");
                        DestroyImmediate(source);
                    }

                    GameObject Prefab = (Resources.Load(LocalizationManager.GlobalSources[0]) as GameObject);
                    Selection.activeGameObject = Prefab;
                };
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.Space(10);
        }
Example #28
0
 static void AutoRegister()
 {
     LocalizationManager.RegisterTarget(new LocalizeTarget_UnityStd_AudioSource());
 }
 public static void CallLocalizeAll()
 {
     LocalizationManager.LocalizeAll(true);
     HandleUtility.Repaint();
 }
        public string Import_Google_Result(string JsonString, eSpreadsheetUpdateMode UpdateMode)
        {
            string ErrorMsg = string.Empty;

            if (string.IsNullOrEmpty(JsonString) || JsonString == "\"\"")
            {
                Debug.Log("Language Source was up to date");
                return(ErrorMsg);
            }

            if (UpdateMode == eSpreadsheetUpdateMode.Replace)
            {
                ClearAllData();
            }

            int idxV  = JsonString.IndexOf("version=");
            int idxSV = JsonString.IndexOf("script_version=");

            if (idxV < 0 || idxSV < 0)
            {
                return("Invalid Response from Google, Most likely the WebService needs to be updated");
            }

            idxV  += "version=".Length;
            idxSV += "script_version=".Length;

            Google_LastUpdatedVersion = JsonString.Substring(idxV, JsonString.IndexOf(",", idxV) - idxV);
            var version = int.Parse(JsonString.Substring(idxSV, JsonString.IndexOf(",", idxSV) - idxSV));

            if (version != LocalizationManager.GetRequiredWebServiceVersion())
            {
                return("The current Google WebService is not supported.\nPlease, delete the WebService from the Google Drive and Install the latest version.");
            }

            int CSVstartIdx = JsonString.IndexOf("[i2category]");

            while (CSVstartIdx > 0)
            {
                CSVstartIdx += "[i2category]".Length;
                int    endCat   = JsonString.IndexOf("[/i2category]", CSVstartIdx);
                string category = JsonString.Substring(CSVstartIdx, endCat - CSVstartIdx);
                endCat += "[/i2category]".Length;

                int    endCSV = JsonString.IndexOf("[/i2csv]", endCat);
                string csv    = JsonString.Substring(endCat, endCSV - endCat);

                CSVstartIdx = JsonString.IndexOf("[i2category]", endCSV);

                Import_I2CSV(category, csv, UpdateMode);

                // Only the first CSV should clear the Data
                if (UpdateMode == eSpreadsheetUpdateMode.Replace)
                {
                    UpdateMode = eSpreadsheetUpdateMode.Merge;
                }
            }

#if UNITY_EDITOR
            if (!string.IsNullOrEmpty(ErrorMsg))
            {
                UnityEditor.EditorUtility.SetDirty(this);
            }
#endif
            return(ErrorMsg);
        }