public void UnloadLanguage(int languageIndex)
        {
            if (!AllowUnloadingLanguages())
            {
                return;
            }

            // Some consoles don't allow IO access
            if (!PersistentStorage.CanAccessFiles())
            {
                return;
            }

            if (!I2Utils.IsPlaying() ||
                !mLanguages[languageIndex].IsLoaded() ||
                !mLanguages[languageIndex].CanBeUnloaded() ||
                IsCurrentLanguage(languageIndex) ||
                !PersistentStorage.HasFile(PersistentStorage.eFileType.Temporal, GetSavedLanguageFileName(languageIndex)))
            {
                return;
            }

            foreach (var termData in mTerms)
            {
                termData.Languages[languageIndex] = null;
            }
            mLanguages[languageIndex].SetLoaded(false);
        }
Ejemplo n.º 2
0
        public override void DoLocalize(Localize cmp, string mainTranslation, string secondaryTranslation)
        {
            //--[ Localize Font Object ]----------
            {
                TMPro.TMP_FontAsset newFont = cmp.GetSecondaryTranslatedObj<TMPro.TMP_FontAsset>(ref mainTranslation, ref secondaryTranslation);

                if (newFont != null)
                {
                    if (mTarget.font != newFont)
                        mTarget.font = newFont;
                }
                else
                {
                    //--[ Localize Font Material ]----------
                    Material newMat = cmp.GetSecondaryTranslatedObj<Material>(ref mainTranslation, ref secondaryTranslation);
                    if (newMat != null && mTarget.fontMaterial != newMat)
                    {
                        if (!newMat.name.StartsWith(mTarget.font.name, StringComparison.Ordinal))
                        {
                            newFont = GetTMPFontFromMaterial(cmp, secondaryTranslation.EndsWith(newMat.name, StringComparison.Ordinal) ? secondaryTranslation : newMat.name);
                            if (newFont != null)
                                mTarget.font = newFont;
                        }

                        mTarget.fontSharedMaterial/* fontMaterial*/ = newMat;
                    }
                }
            }
            if (mInitializeAlignment)
            {
                mInitializeAlignment = false;
                mAlignmentWasRTL = LocalizationManager.IsRight2Left;
                InitAlignment_TMPro(mAlignmentWasRTL, mTarget.alignment, out mAlignment_LTR, out mAlignment_RTL);
            }
            else
            {
                TMPro.TextAlignmentOptions alignRTL, alignLTR;
                InitAlignment_TMPro(mAlignmentWasRTL, mTarget.alignment, out alignLTR, out alignRTL);

                if ((mAlignmentWasRTL && mAlignment_RTL != alignRTL) ||
                    (!mAlignmentWasRTL && mAlignment_LTR != alignLTR))
                {
                    mAlignment_LTR = alignLTR;
                    mAlignment_RTL = alignRTL;
                }
                mAlignmentWasRTL = LocalizationManager.IsRight2Left;
            }

            if (mainTranslation != null && mTarget.text != mainTranslation)
            {
                if (mainTranslation != null && cmp.CorrectAlignmentForRTL)
                {
                    mTarget.alignment = (LocalizationManager.IsRight2Left ? mAlignment_RTL : mAlignment_LTR);
                    mTarget.isRightToLeftText = LocalizationManager.IsRight2Left;
                    if (LocalizationManager.IsRight2Left) mainTranslation = I2Utils.ReverseText(mainTranslation);
                }

                mTarget.text = mainTranslation;
            }
        }
Ejemplo n.º 3
0
        public UnityWebRequest Import_Google_CreateWWWcall(bool ForceUpdate, bool justCheck)
        {
            if (!HasGoogleSpreadsheet())
            {
                return(null);
            }

            string savedVersion = PersistentStorage.GetSetting_String("I2SourceVersion_" + GetSourcePlayerPrefName(), Google_LastUpdatedVersion);

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

#if !UNITY_EDITOR
            if (IsNewerVersion(savedVersion, Google_LastUpdatedVersion))
            {
                Google_LastUpdatedVersion = savedVersion;
            }
#endif

            string query = string.Format("{0}?key={1}&action=GetLanguageSource&version={2}",
                                         LocalizationManager.GetWebServiceURL(this),
                                         Google_SpreadsheetKey,
                                         ForceUpdate ? "0" : Google_LastUpdatedVersion);
#if UNITY_EDITOR
            if (justCheck)
            {
                query += "&justcheck=true";
            }
#endif
            UnityWebRequest www = UnityWebRequest.Get(query);
            I2Utils.SendWebRequest(www);
            return(www);
        }
        public void LoadLanguage(int languageIndex, bool UnloadOtherLanguages, bool useFallback, bool onlyCurrentSpecialization, bool forceLoad)
        {
            if (!AllowUnloadingLanguages())
            {
                return;
            }

            // Some consoles don't allow IO access
            if (!PersistentStorage.CanAccessFiles())
            {
                return;
            }

            if (languageIndex >= 0 && (forceLoad || !mLanguages[languageIndex].IsLoaded()))
            {
                var tempPath = GetSavedLanguageFileName(languageIndex);
                var langData = PersistentStorage.LoadFile(PersistentStorage.eFileType.Temporal, tempPath, false);

                if (!string.IsNullOrEmpty(langData))
                {
                    Import_Language_from_Cache(languageIndex, langData, useFallback, onlyCurrentSpecialization);
                    mLanguages[languageIndex].SetLoaded(true);
                }
            }
            if (UnloadOtherLanguages && I2Utils.IsPlaying())
            {
                for (int lan = 0; lan < mLanguages.Count; ++lan)
                {
                    if (lan != languageIndex)
                    {
                        UnloadLanguage(lan);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        static void AddObjectPath(ref string sPath, Localize localizeCmp, Object NewObj)
        {
            if (I2Utils.RemoveResourcesPath(ref sPath))
            {
                return;
            }

            // If its not in the Resources folder and there is no object reference already in the
            // Reference array, then add that to the Localization component or the Language Source
            if (HasObjectInReferences(NewObj, localizeCmp))
            {
                return;
            }

            if (localizeCmp != null)
            {
                localizeCmp.AddTranslatedObject(NewObj);
                EditorUtility.SetDirty(localizeCmp);
            }
            else
            if (mLanguageSource != null)
            {
                mLanguageSource.AddAsset(NewObj);
                mLanguageSource.Editor_SetDirty();
            }
        }
Ejemplo n.º 6
0
        string ScriptTool_AdjustTerm(string Term, bool allowFullLength = false)
        {
            Term = I2Utils.GetValidTermName(Term);

            // C# IDs can't start with a number
            if (I2Utils.NumberChars.IndexOf(Term[0]) >= 0)
            {
                Term = "_" + Term;
            }

            if (!allowFullLength && Term.Length > Script_Tool_MaxVariableLength)
            {
                Term = Term.Substring(0, Script_Tool_MaxVariableLength);
            }

            // Remove invalid characters
            char[] chars = Term.ToCharArray();
            for (int i = 0, imax = chars.Length; i < imax; ++i)
            {
                if (I2Utils.ValidChars.IndexOf(chars[i]) < 0)
                {
                    chars[i] = '_';
                }
            }
            return(new string(chars));
        }
        static void ParseTermsInScripts()
        {
            EditorApplication.update -= ParseTermsInScripts;

            string[] scriptFiles = AssetDatabase.GetAllAssetPaths().Where(path => path.ToLower().EndsWith(".cs")).ToArray();

            string mLocalizationManager    = @"GetTranslation\s?\(\s?\""(.*?)\""";
            string mLocalizationManagerOld = @"GetTermTranslation\s?\(\s?\""(.*?)\""";
            string mLocalizationManagerTry = @"TryGetTranslation\s?\(\s?\""(.*?)\""";
            string mSetTerm = @"SetTerm\s?\(\s?\""(.*?)\""";

            Regex regex = new Regex(mLocalizationManager + "|" + mLocalizationManagerTry + "|" + mLocalizationManagerOld + "|" + mSetTerm, RegexOptions.Multiline);

            foreach (string scriptFile in scriptFiles)
            {
                string          scriptContents = File.ReadAllText(scriptFile);
                MatchCollection matches        = regex.Matches(scriptContents);
                for (int matchNum = 0; matchNum < matches.Count; matchNum++)
                {
                    Match  match = matches[matchNum];
                    string term  = I2Utils.GetCaptureMatch(match);
                    GetParsedTerm(term).Usage++;
                }
            }
            ScheduleUpdateTermsToShowInList();
        }
        static TermData AddTerm(string Term, bool AutoSelect = true, eTermType termType = eTermType.Text)
        {
            if (Term == "-" || string.IsNullOrEmpty(Term))
            {
                return(null);
            }

            Term = I2Utils.RemoveNonASCII(Term, true);

            TermData data = mLanguageSource.AddTerm(Term, termType);

            GetParsedTerm(Term);
            string sCategory = LanguageSource.GetCategoryFromFullTerm(Term);

            mParsedCategories.Add(sCategory);

            if (AutoSelect)
            {
                if (!mSelectedKeys.Contains(Term))
                {
                    mSelectedKeys.Add(Term);
                }

                if (!mSelectedCategories.Contains(sCategory))
                {
                    mSelectedCategories.Add(sCategory);
                }
            }
            ScheduleUpdateTermsToShowInList();
            EditorUtility.SetDirty(mLanguageSource);
            return(data);
        }
Ejemplo n.º 9
0
        public void UpdateDictionary(bool force = false)
        {
            if (!force && mDictionary != null && mDictionary.Count == mTerms.Count)
            {
                return;
            }

            StringComparer comparer = (CaseInsensitiveTerms ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);

            if (mDictionary.Comparer != comparer)
            {
                mDictionary = new Dictionary <string, TermData>(comparer);
            }
            else
            {
                mDictionary.Clear();
            }

            for (int i = 0, imax = mTerms.Count; i < imax; ++i)
            {
                var termData = mTerms[i];
                ValidateFullTerm(ref termData.Term);

                mDictionary[termData.Term] = mTerms[i];
                mTerms[i].Validate();
            }

            if (I2Utils.IsPlaying())
            {
                SaveLanguages(true);
            }
        }
        void Google_NewSpreadsheet()
        {
                        #if UNITY_WEBPLAYER
            ShowError("Contacting google translation is not yet supported on WebPlayer");
                        #else
            ClearErrors();
            string SpreadsheetName;

            LanguageSourceData source = GetSourceData();
            if (source.IsGlobalSource())
            {
                SpreadsheetName = string.Format("{0} Localization", PlayerSettings.productName);
            }
            else
            {
                SpreadsheetName = string.Format("{0} {1} {2}", PlayerSettings.productName, Editor_GetCurrentScene(), source.ownerObject.name);
            }

            string query = mProp_Google_WebServiceURL.stringValue + "?action=NewSpreadsheet&name=" + Uri.EscapeDataString(SpreadsheetName) + "&password="******"Creating Spreadsheet";
            //mConnection_TimeOut = Time.realtimeSinceStartup + 10;
                        #endif
        }
        static void ParseNonTranslatableElements(ref TranslationQuery query)
        {
            //\[i2nt].*\[\/i2nt]
            var matches = Regex.Matches(query.Text, @"\{\[(.*?)]}|\[(.*?)]|\<(.*?)>");

            if (matches == null || matches.Count == 0)
            {
                return;
            }

            string        finalText = query.Text;
            List <string> finalTags = new List <string>();

            for (int i = 0, imax = matches.Count; i < imax; ++i)
            {
                var tag         = I2Utils.GetCaptureMatch(matches[i]);
                int iClosingTag = FindClosingTag(tag, matches, i); //  find [/tag] or </tag>

                if (iClosingTag < 0)
                {
                    // Its not a tag, its a parameter
                    var fulltag = matches[i].ToString();
                    if (fulltag.StartsWith("{[") && fulltag.EndsWith("]}"))
                    {
                        finalText = finalText.Replace(fulltag, GetGoogleNoTranslateTag(finalTags.Count) + " ");  //  0x2600 is the start of the UNICODE Miscellaneous Symbols table, so they are not going to be translated by google
                        //finalText = finalText.Replace(fulltag, /*"{[" + finalTags.Count + "]}"*/ ((char)(0x2600 + finalTags.Count)).ToString());  //  0x2600 is the start of the UNICODE Miscellaneous Symbols table, so they are not going to be translated by google
                        finalTags.Add(fulltag);
                    }
                    continue;
                }

                if (tag == "i2nt")
                {
                    var tag1 = query.Text.Substring(matches[i].Index, (matches[iClosingTag].Index - matches[i].Index) + matches[iClosingTag].Length);
                    finalText = finalText.Replace(tag1, GetGoogleNoTranslateTag(finalTags.Count) + " ");
                    //finalText = finalText.Replace(tag1, /*"{[" + finalTags.Count + "]}"*/ ((char)(0x2600 + finalTags.Count)).ToString());

                    finalTags.Add(tag1);
                }
                else
                {
                    var tag1 = matches[i].ToString();
                    finalText = finalText.Replace(tag1, GetGoogleNoTranslateTag(finalTags.Count) + " ");
                    //finalText = finalText.Replace(tag1, /*"{[" + finalTags.Count + "]}"*/ ((char)(0x2600 + finalTags.Count)).ToString());
                    finalTags.Add(tag1);

                    var tag2 = matches[iClosingTag].ToString();
                    finalText = finalText.Replace(tag2, GetGoogleNoTranslateTag(finalTags.Count) + " ");
                    //finalText = finalText.Replace(tag2, /*"{[" + finalTags.Count + "]}"*/ ((char)(0x2600 + finalTags.Count)).ToString());
                    finalTags.Add(tag2);
                }
            }

            query.Text = finalText;
            query.Tags = finalTags.ToArray();
        }
 static int FindClosingTag(string tag, MatchCollection matches, int startIndex)
 {
     for (int i = startIndex, imax = matches.Count; i < imax; ++i)
     {
         var newTag = I2Utils.GetCaptureMatch(matches[i]);
         if (newTag[0] == '/' && tag.StartsWith(newTag.Substring(1)))
         {
             return(i);
         }
     }
     return(-1);
 }
Ejemplo n.º 13
0
        public void Import_Google_FromCache()
        {
            if (GoogleUpdateFrequency == eGoogleUpdateFrequency.Never)
            {
                return;
            }

            if (!I2Utils.IsPlaying())
            {
                return;
            }

            string PlayerPrefName = GetSourcePlayerPrefName();
            string I2SavedData    = PersistentStorage.LoadFile(PersistentStorage.eFileType.Persistent, "I2Source_" + PlayerPrefName + ".loc", false);

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

            if (I2SavedData.StartsWith("[i2e]", StringComparison.Ordinal))
            {
                I2SavedData = StringObfucator.Decode(I2SavedData.Substring(5, I2SavedData.Length - 5));
            }

            //--[ Compare with current version ]-----
            bool   shouldUpdate            = false;
            string savedSpreadsheetVersion = Google_LastUpdatedVersion;

            if (PersistentStorage.HasSetting("I2SourceVersion_" + PlayerPrefName))
            {
                savedSpreadsheetVersion = PersistentStorage.GetSetting_String("I2SourceVersion_" + PlayerPrefName, Google_LastUpdatedVersion);
//				Debug.Log (Google_LastUpdatedVersion + " - " + savedSpreadsheetVersion);
                shouldUpdate = IsNewerVersion(Google_LastUpdatedVersion, savedSpreadsheetVersion);
            }

            if (!shouldUpdate)
            {
                PersistentStorage.DeleteFile(PersistentStorage.eFileType.Persistent, "I2Source_" + PlayerPrefName + ".loc", false);
                PersistentStorage.DeleteSetting("I2SourceVersion_" + PlayerPrefName);
                return;
            }

            if (savedSpreadsheetVersion.Length > 19)             // Check for corruption from previous versions
            {
                savedSpreadsheetVersion = string.Empty;
            }
            Google_LastUpdatedVersion = savedSpreadsheetVersion;

            //Debug.Log ("[I2Loc] Using Saved (PlayerPref) data in 'I2Source_"+PlayerPrefName+"'" );
            Import_Google_Result(I2SavedData, eSpreadsheetUpdateMode.Replace);
        }
        void Google_FindSpreadsheets()
        {
            ClearErrors();
            EditorApplication.update -= Google_FindSpreadsheets;
            string query = mProp_Google_WebServiceURL.stringValue + "?action=GetSpreadsheetList&password="******"Accessing google";
            //mConnection_TimeOut = Time.realtimeSinceStartup + 10;
        }
Ejemplo n.º 15
0
 public static void ValidateFullTerm(ref string Term)
 {
     Term = Term.Replace('\\', '/');
     Term = Term.Trim();
     if (Term.StartsWith(EmptyCategory, StringComparison.Ordinal))
     {
         if (Term.Length > EmptyCategory.Length && Term[EmptyCategory.Length] == '/')
         {
             Term = Term.Substring(EmptyCategory.Length + 1);
         }
     }
     Term = I2Utils.RemoveNonASCII(Term, true);
 }
Ejemplo n.º 16
0
        void ExecuteNextBatch()
        {
            if (mQueries.Count == 0)
            {
                mJobState = eJobState.Succeeded;
                return;
            }
            mCurrentBatch_Text = new List <string>();

            string lastLangCode = null;
            int    maxLength    = 200;

            var sb = new StringBuilder();
            int i;

            for (i = 0; i < mQueries.Count; ++i)
            {
                var text     = mQueries[i].Key;
                var langCode = mQueries[i].Value;

                if (lastLangCode == null || langCode == lastLangCode)
                {
                    if (i != 0)
                    {
                        sb.Append("|||");
                    }
                    sb.Append(text);

                    mCurrentBatch_Text.Add(text);
                    lastLangCode = langCode;
                }
                if (sb.Length > maxLength)
                {
                    break;
                }
            }
            mQueries.RemoveRange(0, i);

            var fromtoLang = lastLangCode.Split(':');

            mCurrentBatch_FromLanguageCode = fromtoLang[0];
            mCurrentBatch_ToLanguageCode   = fromtoLang[1];

            string url = string.Format("http://www.google.com/translate_t?hl=en&vi=c&ie=UTF8&oe=UTF8&submit=Translate&langpair={0}|{1}&text={2}", mCurrentBatch_FromLanguageCode, mCurrentBatch_ToLanguageCode, Uri.EscapeUriString(sb.ToString()));

            Debug.Log(url);

            www = UnityWebRequest.Get(url);
            I2Utils.SendWebRequest(www);
        }
        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 = UnityWebRequest.Post(LocalizationManager.GetWebServiceURL(), form);
            I2Utils.SendWebRequest(www);
        }
 void VerifyGoogleService(string WebServiceURL)
 {
                 #if UNITY_WEBPLAYER
     ShowError("Contacting google translation is not yet supported on WebPlayer");
                 #else
     StopConnectionWWW();
     mWebService_Status = null;
     mConnection_WWW    = UnityWebRequest.Get(WebServiceURL + "?action=Ping");
     I2Utils.SendWebRequest(mConnection_WWW);
     mConnection_Callback      = OnVerifyGoogleService;
     EditorApplication.update += CheckForConnection;
     mConnection_Text          = "Verifying Web Service";
     //mConnection_TimeOut = Time.realtimeSinceStartup + 10;
                 #endif
 }
Ejemplo n.º 19
0
        void FillValues()
        {
            var _Dropdown = GetComponent <Dropdown>();

            if (_Dropdown == null && I2Utils.IsPlaying())
            {
                #if TextMeshPro
                FillValuesTMPro();
                #endif
                return;
            }

            foreach (var term in _Dropdown.options)
            {
                _Terms.Add(term.text);
            }
        }
Ejemplo n.º 20
0
        public void UnloadLanguage(int languageIndex)
        {
            if (!I2Utils.IsPlaying() ||
                !mLanguages[languageIndex].IsLoaded() ||
                !mLanguages[languageIndex].CanBeUnloaded() ||
                IsCurrentLanguage(languageIndex) ||
                !PersistentStorage.HasFile(GetSavedLanguageFileName(languageIndex)))
            {
                return;
            }

            foreach (var termData in mTerms)
            {
                termData.Languages[languageIndex] = termData.Languages_Touch[languageIndex] = null;
            }
            mLanguages[languageIndex].SetLoaded(false);
        }
Ejemplo n.º 21
0
        void ExecuteNextQuery()
        {
            if (mQueries.Count == 0)
            {
                mJobState = eJobState.Succeeded;
                return;
            }

            int lastQuery = mQueries.Count - 1;
            var query     = mQueries[lastQuery];

            mQueries.RemoveAt(lastQuery);

            string url = string.Format("{0}?action=Translate&list={1}", LocalizationManager.GetWebServiceURL(), query);

            www = UnityWebRequest.Get(url);
            I2Utils.SendWebRequest(www);
        }
Ejemplo n.º 22
0
        // Returns the term that will actually be translated
        // its either the Term value in this class or the text of the label if there is no term
        public void GetFinalTerms(out string primaryTerm, out string secondaryTerm)
        {
            primaryTerm   = string.Empty;
            secondaryTerm = string.Empty;

            if (!FindTarget())
            {
                return;
            }


            // if either the primary or secondary term is missing, get them. (e.g. from the label's text and font name)
            if (mLocalizeTarget != null)
            {
                mLocalizeTarget.GetFinalTerms(this, mTerm, mTermSecondary, out primaryTerm, out secondaryTerm);
                primaryTerm = I2Utils.GetValidTermName(primaryTerm, false);
            }

            // If there are values already set, go with those
            if (!string.IsNullOrEmpty(mTerm))
            {
                primaryTerm = mTerm;
            }

            if (!string.IsNullOrEmpty(mTermSecondary))
            {
                secondaryTerm = mTermSecondary;
            }

            if (primaryTerm != null)
            {
                primaryTerm = primaryTerm.Trim();
            }
            if (secondaryTerm != null)
            {
                secondaryTerm = secondaryTerm.Trim();
            }
        }
        public override void GetFinalTerms(Localize cmp, string Main, string Secondary, out string primaryTerm, out string secondaryTerm)
        {
            if (mTarget == null)
            {
                primaryTerm = secondaryTerm = null;
            }
            else
            {
                MeshFilter filter = mTarget.GetComponent <MeshFilter>();
                if (filter == null || filter.sharedMesh == null)
                {
                    primaryTerm = null;
                }
                else
                {
                    #if UNITY_EDITOR
                    primaryTerm = UnityEditor.AssetDatabase.GetAssetPath(filter.sharedMesh);
                    I2Utils.RemoveResourcesPath(ref primaryTerm);
                    #else
                    primaryTerm = filter.sharedMesh.name;
                    #endif
                }
            }

            if (mTarget == null || mTarget.sharedMaterial == null)
            {
                secondaryTerm = null;
            }
            else
            {
                #if UNITY_EDITOR
                secondaryTerm = UnityEditor.AssetDatabase.GetAssetPath(mTarget.sharedMaterial);
                I2Utils.RemoveResourcesPath(ref secondaryTerm);
                #else
                secondaryTerm = mTarget.sharedMaterial.name;
                #endif
            }
        }
Ejemplo n.º 24
0
        public void LoadLanguage(int languageIndex, bool UnloadOtherLanguages, bool useFallback)
        {
            if (languageIndex >= 0 && !mLanguages[languageIndex].IsLoaded())
            {
                var tempPath = GetSavedLanguageFileName(languageIndex);
                var langData = PersistentStorage.LoadFile(tempPath);

                if (!string.IsNullOrEmpty(langData))
                {
                    Import_Language(languageIndex, langData, useFallback);
                    mLanguages[languageIndex].SetLoaded(true);
                }
            }
            if (UnloadOtherLanguages && I2Utils.IsPlaying())
            {
                for (int lan = 0; lan < mLanguages.Count; ++lan)
                {
                    if (lan != languageIndex)
                    {
                        UnloadLanguage(lan);
                    }
                }
            }
        }
        public UnityWebRequest Export_Google_CreateWWWcall(eSpreadsheetUpdateMode UpdateMode = eSpreadsheetUpdateMode.Replace)
        {
            #if UNITY_WEBPLAYER
            Debug.Log("Contacting google translation is not yet supported on WebPlayer");
            return(null);
#else
            string Data = Export_Google_CreateData();

            WWWForm form = new WWWForm();
            form.AddField("key", Google_SpreadsheetKey);
            form.AddField("action", "SetLanguageSource");
            form.AddField("data", Data);
            form.AddField("updateMode", UpdateMode.ToString());

            #if UNITY_EDITOR
            form.AddField("password", Google_Password);
#endif


            UnityWebRequest www = UnityWebRequest.Post(LocalizationManager.GetWebServiceURL(this), form);
            I2Utils.SendWebRequest(www);
            return(www);
                        #endif
        }
Ejemplo n.º 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 && !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;
        }
Ejemplo n.º 27
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.SaveFile(PersistentStorage.eFileType.Persistent, "I2Source_" + PlayerPrefName, "[i2e]" + StringObfucator.Encode(JsonString) + ".loc");
                    PersistentStorage.SetSetting_String("I2SourceVersion_" + PlayerPrefName, newSpreadsheetVersion);
                    PersistentStorage.ForceSaveSettings();
                }
                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 (I2Utils.IsPlaying())
                {
                    SaveLanguages(true);
                }

#if UNITY_EDITOR
                if (!string.IsNullOrEmpty(ErrorMsg))
                {
                    UnityEditor.EditorUtility.SetDirty(this);
                }
#endif
                return(ErrorMsg);
            }
            catch (System.Exception e)
            {
                Debug.LogWarning(e);
                return(e.ToString());
            }
        }
Ejemplo n.º 28
0
        // When JustCheck is true, importing from google will not download any data, just detect if the Spreadsheet is up-to-date
        public void Import_Google(bool ForceUpdate, bool justCheck)
        {
            if (!ForceUpdate && GoogleUpdateFrequency == eGoogleUpdateFrequency.Never)
            {
                return;
            }

            if (!I2Utils.IsPlaying())
            {
                return;
            }

            #if UNITY_EDITOR
            if (justCheck && GoogleInEditorCheckFrequency == eGoogleUpdateFrequency.Never)
            {
                return;
            }
            #endif

            #if UNITY_EDITOR
            var updateFrequency = GoogleInEditorCheckFrequency;
            #else
            var updateFrequency = GoogleUpdateFrequency;
            #endif

            string PlayerPrefName = GetSourcePlayerPrefName();
            if (!ForceUpdate && updateFrequency != eGoogleUpdateFrequency.Always)
            {
                #if UNITY_EDITOR
                string sTimeOfLastUpdate = UnityEditor.EditorPrefs.GetString("LastGoogleUpdate_" + PlayerPrefName, "");
                #else
                string sTimeOfLastUpdate = PersistentStorage.GetSetting_String("LastGoogleUpdate_" + PlayerPrefName, "");
                #endif
                DateTime TimeOfLastUpdate;
                try
                {
                    if (DateTime.TryParse(sTimeOfLastUpdate, out TimeOfLastUpdate))
                    {
                        double TimeDifference = (DateTime.Now - TimeOfLastUpdate).TotalDays;
                        switch (updateFrequency)
                        {
                        case eGoogleUpdateFrequency.Daily: if (TimeDifference < 1)
                            {
                                return;
                            }
                            break;

                        case eGoogleUpdateFrequency.Weekly: if (TimeDifference < 8)
                            {
                                return;
                            }
                            break;

                        case eGoogleUpdateFrequency.Monthly: if (TimeDifference < 31)
                            {
                                return;
                            }
                            break;

                        case eGoogleUpdateFrequency.OnlyOnce: return;
                        }
                    }
                }
                catch (Exception)
                { }
            }
            #if UNITY_EDITOR
            UnityEditor.EditorPrefs.SetString("LastGoogleUpdate_" + PlayerPrefName, DateTime.Now.ToString());
            #else
            PersistentStorage.SetSetting_String("LastGoogleUpdate_" + PlayerPrefName, DateTime.Now.ToString());
            #endif

            //--[ Checking google for updated data ]-----------------
            CoroutineManager.Start(Import_Google_Coroutine(justCheck));
        }
Ejemplo n.º 29
0
        public static string ApplyRTLfix(string line, int maxCharacters, bool ignoreNumbers)
        {
            if (string.IsNullOrEmpty(line))
            {
                return(line);
            }

            // Fix !, ? and . signs not set correctly
            char firstC = line[0];

            if (firstC == '!' || firstC == '.' || firstC == '?')
            {
                line = line.Substring(1) + firstC;
            }

            int tagStart = -1, tagEnd = 0;

            // Find all Tags (and Numbers if ignoreNumbers is true)
            int tagBase = 40000;

            tagEnd = 0;
            var tags = new List <string>();

            while (I2Utils.FindNextTag(line, tagEnd, out tagStart, out tagEnd))
            {
                string tag = "@@" + (char)(tagBase + tags.Count) + "@@";
                tags.Add(line.Substring(tagStart, tagEnd - tagStart + 1));

                line   = line.Substring(0, tagStart) + tag + line.Substring(tagEnd + 1);
                tagEnd = tagStart + 5;
            }

            // Split into lines and fix each line
            line = line.Replace("\r\n", "\n");
            line = I2Utils.SplitLine(line, maxCharacters);
            line = RTLFixer.Fix(line, true, !ignoreNumbers);


            // Restore all tags

            for (int i = 0; i < tags.Count; i++)
            {
                var len = line.Length;

                for (int j = 0; j < len; ++j)
                {
                    if (line[j] == '@' && line[j + 1] == '@' && line[j + 2] >= tagBase && line[j + 3] == '@' && line[j + 4] == '@')
                    {
                        int idx = line[j + 2] - tagBase;
                        if (idx % 2 == 0)
                        {
                            idx++;
                        }
                        else
                        {
                            idx--;
                        }
                        if (idx >= tags.Count)
                        {
                            idx = tags.Count - 1;
                        }

                        line = line.Substring(0, j) + tags[idx] + line.Substring(j + 5);

                        break;
                    }
                }
            }

            return(line);
        }
Ejemplo n.º 30
0
 public void SetFinalTerms(string Main, string Secondary, out string primaryTerm, out string secondaryTerm, bool RemoveNonASCII)
 {
     primaryTerm   = RemoveNonASCII ? I2Utils.GetValidTermName(Main) : Main;
     secondaryTerm = Secondary;
 }