void StartTranslating(string fromCode, string toCode)
        {
            IsTranslating = true;

            // fromCode could be "auto" to autodetect the language
            GoogleTranslation.Translate(OriginalText, fromCode, toCode, OnTranslationReady);
        }
        static void Translate(string Key, ref TermData termdata, ref string sTarget, string TargetLanguageCode)
        {
                        #if UNITY_WEBPLAYER
            ShowError("Contacting google translation is not yet supported on WebPlayer");
                        #else
            // Translate first language that has something
            // If no language found, translation will fallback to autodetect language from key
            string SourceCode = "auto";
            string text       = Key;

            string[] lans = (GUI_SelectedInputType == 0 ? termdata.Languages : termdata.Languages_Touch);
            for (int i = 0, imax = lans.Length; i < imax; ++i)
            {
                if (!string.IsNullOrEmpty(lans[i]))
                {
                    text = lans[i];
                    if (mLanguageSource.mLanguages[i].Code != TargetLanguageCode)
                    {
                        SourceCode = mLanguageSource.mLanguages[i].Code;
                        break;
                    }
                }
            }

            sTarget = GoogleTranslation.ForceTranslate(text, SourceCode, TargetLanguageCode);
                        #endif
        }
Example #3
0
        public TranslationJob_GET(TranslationDictionary requests, Action <TranslationDictionary, string> OnTranslationReady)
        {
            _requests           = requests;
            _OnTranslationReady = OnTranslationReady;

            mQueries = GoogleTranslation.ConvertTranslationRequest(requests, true);

            GetState();
        }
Example #4
0
        void TranslateAllToLanguage(string lanName)
        {
            if (!GoogleTranslation.CanTranslate())
            {
                ShowError("WebService is not set correctly or needs to be reinstalled");
                return;
            }
            ClearErrors();
            int    LanIndex   = mLanguageSource.GetLanguageIndex(lanName);
            string code       = mLanguageSource.mLanguages [LanIndex].Code;
            string googleCode = GoogleLanguages.GetGoogleLanguageCode(code);

            if (string.IsNullOrEmpty(googleCode))
            {
                ShowError("Language '" + code + "' is not supported by google translate");
                return;
            }
            googleCode = code;

            mTranslationTerms.Clear();
            mTranslationRequests.Clear();
            foreach (var termData in mLanguageSource.mTerms)
            {
                if (termData.TermType != eTermType.Text)
                {
                    continue;
                }

                if (!string.IsNullOrEmpty(termData.Languages[LanIndex]))
                {
                    continue;
                }

                string sourceCode, sourceText;
                FindTranslationSource(LanguageSourceData.GetKeyFromFullTerm(termData.Term), termData, code, null, out sourceText, out sourceCode);

                mTranslationTerms.Add(termData.Term);

                GoogleTranslation.CreateQueries(sourceText, sourceCode, googleCode, mTranslationRequests);                   // can split plurals into several queries
            }

            if (mTranslationRequests.Count == 0)
            {
                StopConnectionWWW();
                return;
            }

            mConnection_WWW  = null;
            mConnection_Text = "Translating"; if (mTranslationRequests.Count > 1)
            {
                mConnection_Text += " (" + mTranslationRequests.Count + ")";
            }
            mConnection_Callback = null;
            //EditorApplication.update += CheckForConnection;

            GoogleTranslation.Translate(mTranslationRequests, OnLanguageTranslated);
        }
        public void StartTranslating(string fromCode, string toCode)
        {
            IsTranslating = true;

            // fromCode could be "auto" to autodetect the language
            GoogleTranslation.Translate(OriginalText, fromCode, toCode, OnTranslationReady);

            // can also use the ForceTranslate version: (it will block the main thread until the translation is returned)
            //var translation = GoogleTranslation.ForceTranslate(OriginalText, fromCode, toCode);
            //Debug.Log(translation);
        }
        void OnLanguageTranslated(string Result, string Error)
        {
            //Debug.Log (Result);
            if (!string.IsNullOrEmpty(Error) /* || !Result.Contains("<i2>")*/)
            {
                ShowError("Unable to access Google or not valid request");
                return;
            }

            ClearErrors();
            Error = GoogleTranslation.ParseTranslationResult(Result, mTranslationRequests);
            if (!string.IsNullOrEmpty(Error))
            {
                ShowError(Error);
                return;
            }


            foreach (var request in mTranslationRequests)
            {
                if (request.Results == null)                    // Handle cases where not all translations were valid
                {
                    continue;
                }

                var termData = mLanguageSource.GetTermData(request.Term);
                if (termData == null)
                {
                    continue;
                }

                string lastCode    = "";
                int    lastcodeIdx = 0;

                for (int i = 0; i < request.Results.Length; ++i)
                {
                    //--[ most of the time is a single code, so this works as a cache
                    if (lastCode != request.TargetLanguagesCode[i])
                    {
                        lastCode    = request.TargetLanguagesCode[i];
                        lastcodeIdx = mLanguageSource.GetLanguageIndexFromCode(lastCode);
                    }

                    if (GUI_SelectedInputType == 0)
                    {
                        termData.Languages[lastcodeIdx] = request.Results[i];
                    }
                    else
                    {
                        termData.Languages_Touch[lastcodeIdx] = request.Results[i];
                    }
                }
            }
        }
        public void ExampleMultiTranslations_Async()
        {
            IsTranslating = true;

            // This shows how to ask for many translations
            var dict = new Dictionary <string, TranslationQuery>();

            GoogleTranslation.AddQuery("This is an example", "en", "es", dict);
            GoogleTranslation.AddQuery("This is an example", "auto", "zh", dict);
            GoogleTranslation.AddQuery("Hola", "es", "en", dict);

            GoogleTranslation.Translate(dict, OnMultitranslationReady);
        }
Example #8
0
        public TranslationJob_POST(TranslationDictionary requests, Action <TranslationDictionary, string> OnTranslationReady)
        {
            _requests           = requests;
            _OnTranslationReady = OnTranslationReady;

            var data = GoogleTranslation.ConvertTranslationRequest(requests, false);

            WWWForm form = new WWWForm();

            form.AddField("action", "Translate");
            form.AddField("list", data[0]);

            www = new WWW(LocalizationManager.GetWebServiceURL(), form);
        }
Example #9
0
        public TranslationJob_POST(TranslationDictionary requests, GoogleTranslation.fnOnTranslationReady OnTranslationReady)
        {
            _requests           = requests;
            _OnTranslationReady = OnTranslationReady;

            var data = GoogleTranslation.ConvertTranslationRequest(requests, false);

            WWWForm form = new WWWForm();

            form.AddField("action", "Translate");
            form.AddField("list", data[0]);

            www = UnityWebRequest.Post(LocalizationManager.GetWebServiceURL(), form);
            I2Utils.SendWebRequest(www);
        }
        void OnMultitranslationReady(Dictionary <string, TranslationQuery> dict, string errorMsg)
        {
            if (!string.IsNullOrEmpty(errorMsg))
            {
                Debug.LogError(errorMsg);
                return;
            }

            IsTranslating  = false;
            TranslatedText = "";

            TranslatedText += GoogleTranslation.GetQueryResult("This is an example", "es", dict) + "\n";
            TranslatedText += GoogleTranslation.GetQueryResult("This is an example", "zh", dict) + "\n";
            TranslatedText += GoogleTranslation.GetQueryResult("This is an example", "", dict) + "\n";    // This returns ANY translation of that text (in this case, the first one 'en')
            TranslatedText += dict["Hola"].Results[0];                                                    // example of getting the translation directly from the Results
        }
        string ParseTranslationResult(string html, string OriginalText)
        {
            try
            {
                // This is a Hack for reading Google Translation while Google doens't change their response format
                int iStart = html.IndexOf("TRANSLATED_TEXT='") + "TRANSLATED_TEXT='".Length;
                int iEnd   = html.IndexOf("';var", iStart);

                string Translation = html.Substring(iStart, iEnd - iStart);

                // Convert to normalized HTML
                Translation = System.Text.RegularExpressions.Regex.Replace(Translation,
                                                                           @"\\x([a-fA-F0-9]{2})",
                                                                           match => char.ConvertFromUtf32(Int32.Parse(match.Groups[1].Value, System.Globalization.NumberStyles.HexNumber)));

                // Convert ASCII Characters
                Translation = System.Text.RegularExpressions.Regex.Replace(Translation,
                                                                           @"&#(\d+);",
                                                                           match => char.ConvertFromUtf32(Int32.Parse(match.Groups[1].Value)));

                Translation = Translation.Replace("<br>", "\n");

                if (OriginalText.ToUpper() == OriginalText)
                {
                    Translation = Translation.ToUpper();
                }
                else
                if (GoogleTranslation.UppercaseFirst(OriginalText) == OriginalText)
                {
                    Translation = GoogleTranslation.UppercaseFirst(Translation);
                }
                else
                if (GoogleTranslation.TitleCase(OriginalText) == OriginalText)
                {
                    Translation = GoogleTranslation.TitleCase(Translation);
                }

                return(Translation);
            }
            catch (System.Exception ex)
            {
                Debug.LogError(ex.Message);
                return(string.Empty);
            }
        }
        void DelayedStartTranslation()
        {
            if (EditorApplication.timeSinceStartup < TimeStartTranslation)
            {
                return;
            }
            EditorApplication.update -= DelayedStartTranslation;

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

            mConnection_WWW           = GoogleTranslation.GetTranslationWWW(mTranslationRequests);
            mConnection_Text          = "Translating (" + mTranslationRequests.Count + ")";
            mConnection_Callback      = OnLanguageTranslated;
            EditorApplication.update += CheckForConnection;
        }
        static void Translate(string Key, ref TermData termdata, string TargetLanguageCode, Action <string, string> onTranslated)
        {
                        #if UNITY_WEBPLAYER
            ShowError("Contacting google translation is not yet supported on WebPlayer");
                        #else
            if (!GoogleTranslation.CanTranslate())
            {
                ShowError("WebService is not set correctly or needs to be reinstalled");
                return;
            }

            // Translate first language that has something
            // If no language found, translation will fallback to autodetect language from key

            string sourceCode, sourceText;
            FindTranslationSource(Key, termdata, TargetLanguageCode, out sourceText, out sourceCode);
            GoogleTranslation.Translate(sourceText, sourceCode, TargetLanguageCode, onTranslated);
                        #endif
        }
        public void ExampleMultiTranslations_Blocking()
        {
            // This shows how to ask for many translations
            var dict = new System.Collections.Generic.Dictionary <string, TranslationQuery>();

            GoogleTranslation.AddQuery("This is an example", "en", "es", dict);
            GoogleTranslation.AddQuery("This is an example", "auto", "zh", dict);
            GoogleTranslation.AddQuery("Hola", "es", "en", dict);

            if (!GoogleTranslation.ForceTranslate(dict))
            {
                return;
            }

            Debug.Log(GoogleTranslation.GetQueryResult("This is an example", "en", dict));
            Debug.Log(GoogleTranslation.GetQueryResult("This is an example", "zh", dict));
            Debug.Log(GoogleTranslation.GetQueryResult("This is an example", "", dict)); // This returns ANY translation of that text (in this case, the first one 'en')
            Debug.Log(dict["Hola"].Results[0]);                                          // example of getting the translation directly from the Results
        }
Example #15
0
 public void ProcessResult(byte[] bytes, string errorMsg)
 {
     if (!string.IsNullOrEmpty(errorMsg))
     {
         // check for
         //if (errorMsg.Contains("rewind"))  // "necessary data rewind wasn't possible"
         mJobState = eJobState.Failed;
     }
     else
     {
         var wwwText = Encoding.UTF8.GetString(bytes, 0, bytes.Length); //www.text
         errorMsg = GoogleTranslation.ParseTranslationResult(wwwText, _requests);
         if (_OnTranslationReady != null)
         {
             _OnTranslationReady(_requests, errorMsg);
         }
         mJobState = eJobState.Succeeded;
     }
 }
 static void OnGUI_TranslatingMessage()
 {
     if (GoogleTranslation.IsTranslating())
     {
         // Connection Status Bar
         int    time    = (int)((Time.realtimeSinceStartup % 2) * 2.5);
         string Loading = "Translating" + ".....".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)))
         {
             GoogleTranslation.CancelCurrentGoogleTranslations();
         }
         GUILayout.EndHorizontal();
         HandleUtility.Repaint();
     }
 }
Example #17
0
        public void ProcessResult(byte[] bytes, string errorMsg)
        {
            if (string.IsNullOrEmpty(errorMsg))
            {
                var wwwText = Encoding.UTF8.GetString(bytes, 0, bytes.Length); //www.text
                errorMsg = GoogleTranslation.ParseTranslationResult(wwwText, _requests);

                if (string.IsNullOrEmpty(errorMsg))
                {
                    if (_OnTranslationReady != null)
                    {
                        _OnTranslationReady(_requests, null);
                    }
                    return;
                }
            }

            mJobState     = eJobState.Failed;
            mErrorMessage = errorMsg;
        }
Example #18
0
        // LanguageCodeFrom can be "auto"
        // After the translation is returned from Google, it will call OnTranslationReady(TranslationResult, ErrorMsg)
        // TranslationResult will be null if translation failed
        public static void Translate(string text, string LanguageCodeFrom, string LanguageCodeTo, Action <string, string> OnTranslationReady)
        {
            LocalizationManager.InitializeIfNeeded();
            if (!GoogleTranslation.CanTranslate())
            {
                OnTranslationReady(null, "WebService is not set correctly or needs to be reinstalled");
                return;
            }
            //LanguageCodeTo = GoogleLanguages.GetGoogleLanguageCode(LanguageCodeTo);

            if (LanguageCodeTo == LanguageCodeFrom)
            {
                OnTranslationReady(text, null);
                return;
            }

            TranslationDictionary queries = new TranslationDictionary();


            // Unsupported language
            if (string.IsNullOrEmpty(LanguageCodeTo))
            {
                OnTranslationReady(string.Empty, null);
                return;
            }


            CreateQueries(text, LanguageCodeFrom, LanguageCodeTo, queries);   // can split plurals into several queries

            Translate(queries, (results, error) =>
            {
                if (!string.IsNullOrEmpty(error) || results.Count == 0)
                {
                    OnTranslationReady(null, error);
                    return;
                }

                string result = RebuildTranslation(text, queries, LanguageCodeTo);                                                      // gets the result from google and rebuilds the text from multiple queries if its is plurals
                OnTranslationReady(result, null);
            });
        }
        void TranslateAllToLanguage(string lanName)
        {
            if (!GoogleTranslation.CanTranslate())
            {
                ShowError("WebService is not set correctly or needs to be reinstalled");
                return;
            }

            int    LanIndex = mLanguageSource.GetLanguageIndex(lanName);
            string code     = mLanguageSource.mLanguages [LanIndex].Code;

            mTranslationRequests.Clear();
            foreach (var termData in mLanguageSource.mTerms)
            {
                if (!string.IsNullOrEmpty((GUI_SelectedInputType == 0 ? termData.Languages : termData.Languages_Touch)[LanIndex]))
                {
                    continue;
                }

                string sourceCode, sourceText;
                FindTranslationSource(LanguageSource.GetKeyFromFullTerm(termData.Term), termData, code, out sourceText, out sourceCode);

                mTranslationRequests.Add(new TranslationRequest()
                {
                    Term                = termData.Term,
                    Text                = sourceText,
                    LanguageCode        = sourceCode,
                    TargetLanguagesCode = new string[] { code }
                });
            }

            mConnection_WWW  = GoogleTranslation.GetTranslationWWW(mTranslationRequests);
            mConnection_Text = "Translating"; if (mTranslationRequests.Count > 1)
            {
                mConnection_Text += " (" + mTranslationRequests.Count + ")";
            }
            mConnection_Callback      = OnLanguageTranslated;
            EditorApplication.update += CheckForConnection;
        }
Example #20
0
        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;

            GUI.backgroundColor  = Color.Lerp(GUITools.LightGray, Color.white, 0.5f);
            mScrollPos_Languages = GUILayout.BeginScrollView(mScrollPos_Languages, LocalizeInspector.GUIStyle_OldTextArea, GUILayout.MinHeight(200), /*GUILayout.MaxHeight(Screen.height),*/ GUILayout.ExpandHeight(false));
            GUI.backgroundColor  = Color.white;

            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 (TestButtonArg(eTest_ActionType.Button_Languages_TranslateAll, i, new GUIContent("Translate", "Translate all empty terms"), EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
                {
                    GUITools.DelayedCall(() => TranslateAllToLanguage(LanName));
                }
                GUI.enabled = true;
                GUI.color   = Color.white;

                EditorGUI.BeginChangeCheck();
                isLanguageEnabled = EditorGUILayout.Toggle(isLanguageEnabled, GUILayout.Width(15));

                var r = GUILayoutUtility.GetLastRect();
                GUI.Label(r, new GUIContent("", "Enable/Disable the language.\nDisabled languages can be used to store data values or to avoid showing Languages that are stil under development"));

                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(LocalizeInspector.GUIStyle_OldTextArea);
                GUILayout.Label(Loading, EditorStyles.miniLabel);
                GUI.color = Color.white;
                if (GUILayout.Button("Cancel", EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
                {
                    GoogleTranslation.CancelCurrentGoogleTranslations();
                    StopConnectionWWW();
                }
                GUILayout.EndHorizontal();
                Repaint();
            }

            if (IndexLanguageToDelete >= 0)
            {
                if (EditorUtility.DisplayDialog("Confirm delete", "Are you sure you want to delete the selected language", "Yes", "Cancel"))
                {
                    mLanguageSource.RemoveLanguage(mLanguageSource.mLanguages [IndexLanguageToDelete].Name);
                    serializedObject.Update();
                    ParseTerms(true, false, false);
                }
            }

            if (LanguageToMoveUp >= 0)
            {
                SwapLanguages(LanguageToMoveUp, LanguageToMoveUp - 1);
            }
            if (LanguageToMoveDown >= 0)
            {
                SwapLanguages(LanguageToMoveDown, LanguageToMoveDown + 1);
            }
        }
Example #21
0
        void OnLanguageTranslated(Dictionary <string, TranslationQuery> requests, string Error)
        {
            //Debug.Log (Result);

            //if (Result.Contains("Service invoked too many times"))
            //{
            //    TimeStartTranslation = EditorApplication.timeSinceStartup + 1;
            //    EditorApplication.update += DelayedStartTranslation;
            //    mConnection_Text = "Translating (" + mTranslationRequests.Count + ")";
            //    return;
            //}

            //if (!string.IsNullOrEmpty(Error))/* || !Result.Contains("<i2>")*/
            //{
            //    Debug.LogError("WEB ERROR: " + Error);
            //	ShowError ("Unable to access Google or not valid request");
            //	return;
            //}

            ClearErrors();
            StopConnectionWWW();

            if (!string.IsNullOrEmpty(Error))
            {
                ShowError(Error);
                return;
            }

            if (requests.Values.Count == 0)
            {
                return;
            }

            var langCode = requests.Values.First().TargetLanguagesCode [0];
            //langCode = GoogleLanguages.GetGoogleLanguageCode(langCode);
            int langIndex = mLanguageSource.GetLanguageIndexFromCode(langCode, false);

            //if (langIndex >= 0)
            {
                foreach (var term in mTranslationTerms)
                {
                    var termData = mLanguageSource.GetTermData(term, false);
                    if (termData == null)
                    {
                        continue;
                    }
                    if (termData.TermType != eTermType.Text)
                    {
                        continue;
                    }
                    //if (termData.Languages.Length <= langIndex)
                    //  continue;

                    string sourceCode, sourceText;
                    FindTranslationSource(LanguageSourceData.GetKeyFromFullTerm(termData.Term), termData, langCode, null, out sourceText, out sourceCode);

                    string result = GoogleTranslation.RebuildTranslation(sourceText, mTranslationRequests, langCode);               // gets the result from google and rebuilds the text from multiple queries if its is plurals

                    termData.Languages[langIndex] = result;
                }
            }

            mTranslationTerms.Clear();
            mTranslationRequests.Clear();
            StopConnectionWWW();
        }
Example #22
0
 private void StartTranslating(string fromCode, string toCode)
 {
     IsTranslating = true;
     GoogleTranslation.Translate(OriginalText, fromCode, toCode, OnTranslationReady);
 }
Example #23
0
        public void OnLocalize(bool Force = false)
        {
            if (!Force && (!enabled || gameObject == null || !gameObject.activeInHierarchy))
            {
                return;
            }

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

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

            // 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 = I2Utils.IsPlaying() && HasCallback();

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

            CallBackTerm          = FinalTerm;
            CallBackSecondaryTerm = FinalSecondaryTerm;
            MainTranslation       = (string.IsNullOrEmpty(FinalTerm) || FinalTerm == "-") ? null : LocalizationManager.GetTranslation(FinalTerm, false);
            SecondaryTranslation  = (string.IsNullOrEmpty(FinalSecondaryTerm) || FinalSecondaryTerm == "-") ? null : LocalizationManager.GetTranslation(FinalSecondaryTerm, false);

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

            CurrentLocalizeComponent = this;

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

            if (!FindTarget())
            {
                return;
            }
            bool applyRTL = LocalizationManager.IsRight2Left && !IgnoreRTL;

            if (MainTranslation != null)
            {
                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;
                }
                if (!string.IsNullOrEmpty(TermPrefix))
                {
                    MainTranslation = applyRTL ? MainTranslation + TermPrefix : TermPrefix + MainTranslation;
                }
                if (!string.IsNullOrEmpty(TermSuffix))
                {
                    MainTranslation = applyRTL ? TermSuffix + MainTranslation : MainTranslation + TermSuffix;
                }

                if (AddSpacesToJoinedLanguages && LocalizationManager.HasJoinedWords && !string.IsNullOrEmpty(MainTranslation))
                {
                    var sb = new System.Text.StringBuilder();
                    sb.Append(MainTranslation[0]);
                    for (int i = 1, imax = MainTranslation.Length; i < imax; ++i)
                    {
                        sb.Append(' ');
                        sb.Append(MainTranslation[i]);
                    }

                    MainTranslation = sb.ToString();
                }
                if (applyRTL && mLocalizeTarget.AllowMainTermToBeRTL() && !string.IsNullOrEmpty(MainTranslation))
                {
                    MainTranslation = LocalizationManager.ApplyRTLfix(MainTranslation, MaxCharactersInRTL, IgnoreNumbersInRTL);
                }
            }

            if (SecondaryTranslation != null)
            {
                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;
                }
                if (applyRTL && mLocalizeTarget.AllowSecondTermToBeRTL() && !string.IsNullOrEmpty(SecondaryTranslation))
                {
                    SecondaryTranslation = LocalizationManager.ApplyRTLfix(SecondaryTranslation);
                }
            }

            if (LocalizationManager.HighlightLocalizedTargets)
            {
                MainTranslation = "LOC:" + FinalTerm;
            }

            mLocalizeTarget.DoLocalize(this, MainTranslation, SecondaryTranslation);

            CurrentLocalizeComponent = null;
        }
        void OnLanguageTranslated(string Result, string Error)
        {
            //Debug.Log (Result);

            if (Result.Contains("Service invoked too many times"))
            {
                TimeStartTranslation      = EditorApplication.timeSinceStartup + 1;
                EditorApplication.update += DelayedStartTranslation;
                mConnection_Text          = "Translating (" + mTranslationRequests.Count + ")";
                return;
            }

            if (!string.IsNullOrEmpty(Error))            /* || !Result.Contains("<i2>")*/
            {
                Debug.LogError("WEB ERROR: " + Error);
                ShowError("Unable to access Google or not valid request");
                return;
            }

            ClearErrors();
            Error = GoogleTranslation.ParseTranslationResult(Result, mTranslationRequests);
            if (!string.IsNullOrEmpty(Error))
            {
                ShowError(Error);
                return;
            }


            foreach (var request in mTranslationRequests)
            {
                if (request.Results == null)                    // Handle cases where not all translations were valid
                {
                    continue;
                }

                var termData = mLanguageSource.GetTermData(request.Term);
                if (termData == null)
                {
                    continue;
                }

                string lastCode    = "";
                int    lastcodeIdx = 0;

                for (int i = 0; i < request.Results.Length; ++i)
                {
                    //--[ most of the time is a single code, so this works as a cache
                    if (lastCode != request.TargetLanguagesCode[i])
                    {
                        lastCode    = request.TargetLanguagesCode[i];
                        lastcodeIdx = mLanguageSource.GetLanguageIndexFromCode(lastCode);
                    }

                    if (GUI_SelectedInputType == 0)
                    {
                        termData.Languages[lastcodeIdx] = request.Results[i];
                    }
                    else
                    {
                        termData.Languages_Touch[lastcodeIdx] = request.Results[i];
                    }
                }
            }
            mTranslationRequests.RemoveAll(x => x.Results != null && x.Results.Length > 0);

            if (mTranslationRequests.Count > 0)
            {
                TimeStartTranslation      = EditorApplication.timeSinceStartup + 1;
                EditorApplication.update += DelayedStartTranslation;
                mConnection_Text          = "Translating (" + mTranslationRequests.Count + ")";
            }
        }
Example #25
0
        public void OnLocalize(bool Force = false)
        {
            if ((!Force && (!base.enabled || base.gameObject == null || !base.gameObject.activeInHierarchy)) || string.IsNullOrEmpty(LocalizationManager.CurrentLanguage) || (!AlwaysForceLocalize && !Force && !LocalizeCallBack.HasCallback() && LastLocalizedLanguage == LocalizationManager.CurrentLanguage))
            {
                return;
            }
            LastLocalizedLanguage = LocalizationManager.CurrentLanguage;
            if (!HasTargetCache())
            {
                FindTarget();
            }
            if (!HasTargetCache())
            {
                return;
            }
            if (string.IsNullOrEmpty(FinalTerm) || string.IsNullOrEmpty(FinalSecondaryTerm))
            {
                GetFinalTerms(out FinalTerm, out FinalSecondaryTerm);
            }
            bool flag = Application.isPlaying && LocalizeCallBack.HasCallback();

            if (!flag && string.IsNullOrEmpty(FinalTerm) && string.IsNullOrEmpty(FinalSecondaryTerm))
            {
                return;
            }
            CallBackTerm          = FinalTerm;
            CallBackSecondaryTerm = FinalSecondaryTerm;
            MainTranslation       = ((string.IsNullOrEmpty(FinalTerm) || FinalTerm == "-") ? null : LocalizationManager.GetTermTranslation(FinalTerm, FixForRTL: false));
            SecondaryTranslation  = ((string.IsNullOrEmpty(FinalSecondaryTerm) || FinalSecondaryTerm == "-") ? null : LocalizationManager.GetTermTranslation(FinalSecondaryTerm, FixForRTL: false));
            if (!flag && string.IsNullOrEmpty(FinalTerm) && string.IsNullOrEmpty(SecondaryTranslation))
            {
                return;
            }
            CurrentLocalizeComponent = this;
            if (Application.isPlaying)
            {
                LocalizeCallBack.Execute(this);
                LocalizationManager.ApplyLocalizationParams(ref MainTranslation, base.gameObject);
            }
            bool flag2 = LocalizationManager.IsRight2Left && !IgnoreRTL;

            if (flag2)
            {
                if (AllowMainTermToBeRTL && !string.IsNullOrEmpty(MainTranslation))
                {
                    MainTranslation = LocalizationManager.ApplyRTLfix(MainTranslation, MaxCharactersInRTL, IgnoreNumbersInRTL);
                }
                if (AllowSecondTermToBeRTL && !string.IsNullOrEmpty(SecondaryTranslation))
                {
                    SecondaryTranslation = LocalizationManager.ApplyRTLfix(SecondaryTranslation);
                }
            }
            if (PrimaryTermModifier != 0)
            {
                MainTranslation = (MainTranslation ?? string.Empty);
            }
            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;
            }
            if (SecondaryTermModifier != 0)
            {
                SecondaryTranslation = (SecondaryTranslation ?? string.Empty);
            }
            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;
            }
            if (!string.IsNullOrEmpty(TermPrefix))
            {
                MainTranslation = (flag2 ? (MainTranslation + TermPrefix) : (TermPrefix + MainTranslation));
            }
            if (!string.IsNullOrEmpty(TermSuffix))
            {
                MainTranslation = (flag2 ? (TermSuffix + MainTranslation) : (MainTranslation + TermSuffix));
            }
            EventDoLocalize(MainTranslation, SecondaryTranslation);
            CurrentLocalizeComponent = null;
        }
Example #26
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       = string.IsNullOrEmpty(FinalTerm) || FinalTerm == "-" ? null : LocalizationManager.GetTermTranslation(FinalTerm, false);
            SecondaryTranslation  = string.IsNullOrEmpty(FinalSecondaryTerm) || FinalSecondaryTerm == "-" ? null : LocalizationManager.GetTermTranslation(FinalSecondaryTerm, false);

            if (!hasCallback && /*string.IsNullOrEmpty (MainTranslation)*/ string.IsNullOrEmpty(FinalTerm) && 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);
            }
            bool applyRTL = LocalizationManager.IsRight2Left && !IgnoreRTL;

            if (applyRTL)
            {
                if (AllowMainTermToBeRTL && !string.IsNullOrEmpty(MainTranslation))
                {
                    MainTranslation = LocalizationManager.ApplyRTLfix(MainTranslation, MaxCharactersInRTL, IgnoreNumbersInRTL);
                }
                if (AllowSecondTermToBeRTL && !string.IsNullOrEmpty(SecondaryTranslation))
                {
                    SecondaryTranslation = LocalizationManager.ApplyRTLfix(SecondaryTranslation);
                }
            }

            if (PrimaryTermModifier != TermModification.DontModify)
            {
                MainTranslation = MainTranslation ?? string.Empty;
            }

            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;
            }

            if (SecondaryTermModifier != TermModification.DontModify)
            {
                SecondaryTranslation = SecondaryTranslation ?? string.Empty;
            }

            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;
            }
            if (!string.IsNullOrEmpty(TermPrefix))
            {
                MainTranslation = applyRTL ? MainTranslation + TermPrefix : TermPrefix + MainTranslation;
            }
            if (!string.IsNullOrEmpty(TermSuffix))
            {
                MainTranslation = applyRTL ? TermSuffix + MainTranslation : MainTranslation + TermSuffix;
            }

            EventDoLocalize(MainTranslation, SecondaryTranslation);
            CurrentLocalizeComponent = null;
        }
Example #27
0
        public void OnLocalize(bool Force = false)
        {
            if (!Force && (!enabled || gameObject == null || !gameObject.activeInHierarchy))
            {
                return;
            }

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

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

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

            if (!HasTargetCache())
            {
                return;
            }

            // This 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);
            }

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

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

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

            CurrentLocalizeComponent = this;
            LocalizeCallBack.Execute(this);                // This allows scripts to modify the translations :  e.g. "Player {0} wins"  ->  "Player Red wins"

            if (LocalizationManager.IsRight2Left && !IgnoreRTL)
            {
                if (AllowMainTermToBeRTL && !string.IsNullOrEmpty(MainTranslation))
                {
                    MainTranslation = LocalizationManager.ApplyRTLfix(MainTranslation, MaxCharactersInRTL);
                }
                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;
        }