架构大更

This commit is contained in:
SoulliesOfficial
2026-03-20 11:56:50 -04:00
parent e60ef64d01
commit d09b58fd80
3663 changed files with 15232012 additions and 105579 deletions

View File

@@ -1,17 +1,17 @@
{
"name": "I2",
"rootNamespace": "",
"references": [
"GUID:6055be8ebefd69e48b49212b09b47b2f",
"GUID:75469ad4d38634e559750d17036d5f7c"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
"name": "I2",
"rootNamespace": "",
"references": [
"GUID:6055be8ebefd69e48b49212b09b47b2f",
"GUID:75469ad4d38634e559750d17036d5f7c"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
#if ENABLE_INPUT_SYSTEM
using UnityEngine.InputSystem;
#if ENABLE_INPUT_SYSTEM
using UnityEngine.InputSystem;
#endif
namespace I2.Loc
@@ -13,14 +13,16 @@ namespace I2.Loc
public virtual void InitializeSpecializations()
{
mSpecializations = new[] { "Any", "PC", "Touch", "Controller", "VR",
"XBox", "PS4", "PS5", "OculusVR", "ViveVR", "GearVR", "Android", "IOS",
"Switch"
mSpecializations = new[]
{
"Any", "PC", "Touch", "Controller", "VR",
"XBox", "PS4", "PS5", "OculusVR", "ViveVR", "GearVR", "Android", "IOS",
"Switch"
};
mSpecializationsFallbacks = new Dictionary<string, string>(System.StringComparer.Ordinal)
mSpecializationsFallbacks = new Dictionary<string, string>(StringComparer.Ordinal)
{
{ "XBox", "Controller" }, { "PS4", "Controller" },
{ "OculusVR", "VR" }, { "ViveVR", "VR" }, { "GearVR", "VR" },
{ "OculusVR", "VR" }, { "ViveVR", "VR" }, { "GearVR", "VR" },
{ "Android", "Touch" }, { "IOS", "Touch" }
};
}
@@ -30,30 +32,30 @@ namespace I2.Loc
if (mSpecializations == null)
InitializeSpecializations();
#if UNITY_ANDROID
#if UNITY_ANDROID
return "Android";
#elif UNITY_IOS
#elif UNITY_IOS
return "IOS";
#elif UNITY_PS4
#elif UNITY_PS4
return "PS4";
#elif UNITY_XBOXONE
#elif UNITY_XBOXONE
return "XBox";
#elif UNITY_SWITCH
#elif UNITY_SWITCH
return "Switch";
#elif UNITY_STANDALONE || UNITY_WEBGL
return "PC";
#else
#elif UNITY_STANDALONE || UNITY_WEBGL
return "PC";
#else
return (IsTouchInputSupported() ? "Touch" : "PC");
#endif
#endif
}
bool IsTouchInputSupported()
private bool IsTouchInputSupported()
{
#if ENABLE_INPUT_SYSTEM
return Touchscreen.current != null;
#else
#if ENABLE_INPUT_SYSTEM
return Touchscreen.current != null;
#else
return UnityEngine.Input.touchSupported;
#endif
#endif
}
public virtual string GetFallbackSpecialization(string specialization)
@@ -67,9 +69,10 @@ namespace I2.Loc
return "Any";
}
}
public class SpecializationManager : BaseSpecializationManager
{
public static SpecializationManager Singleton = new SpecializationManager();
public static SpecializationManager Singleton = new();
private SpecializationManager()
{
@@ -88,7 +91,7 @@ namespace I2.Loc
while (!string.IsNullOrEmpty(specialization) && specialization != "Any")
{
var tag = "[i2s_" + specialization + "]";
int idx = text.IndexOf(tag, StringComparison.Ordinal);
var idx = text.IndexOf(tag, StringComparison.Ordinal);
if (idx < 0)
{
specialization = Singleton.GetFallbackSpecialization(specialization);
@@ -109,10 +112,7 @@ namespace I2.Loc
{
if (string.IsNullOrEmpty(specialization))
specialization = "Any";
if ((text==null || !text.Contains("[i2s_")) && specialization=="Any")
{
return newText;
}
if ((text == null || !text.Contains("[i2s_")) && specialization == "Any") return newText;
var dict = GetSpecializations(text);
dict[specialization] = newText;
@@ -120,28 +120,27 @@ namespace I2.Loc
return SetSpecializedText(dict);
}
public static string SetSpecializedText( Dictionary<string,string> specializations )
public static string SetSpecializedText(Dictionary<string, string> specializations)
{
string text;
if (!specializations.TryGetValue("Any", out text))
text = string.Empty;
foreach (var kvp in specializations)
{
if (kvp.Key != "Any" && !string.IsNullOrEmpty(kvp.Value))
text += "[i2s_" + kvp.Key + "]" + kvp.Value;
}
return text;
}
public static Dictionary<string, string> GetSpecializations(string text, Dictionary<string, string> buffer = null)
public static Dictionary<string, string> GetSpecializations(string text,
Dictionary<string, string> buffer = null)
{
if (buffer == null)
buffer = new Dictionary<string, string>(StringComparer.Ordinal);
else
buffer.Clear();
if (text==null)
if (text == null)
{
buffer["Any"] = "";
return buffer;
@@ -150,18 +149,18 @@ namespace I2.Loc
var idxFirst = 0;
var idxEnd = text.IndexOf("[i2s_", StringComparison.Ordinal);
if (idxEnd < 0)
idxEnd=text.Length;
idxEnd = text.Length;
buffer["Any"] = text.Substring(0, idxEnd);
idxFirst = idxEnd;
while (idxFirst<text.Length)
while (idxFirst < text.Length)
{
idxFirst += "[i2s_".Length;
int idx = text.IndexOf(']', idxFirst);
var idx = text.IndexOf(']', idxFirst);
if (idx < 0) break;
var tag = text.Substring(idxFirst, idx - idxFirst);
idxFirst = idx+1; // ']'
idxFirst = idx + 1; // ']'
idxEnd = text.IndexOf("[i2s_", idxFirst, StringComparison.Ordinal);
if (idxEnd < 0) idxEnd = text.Length;
@@ -170,9 +169,11 @@ namespace I2.Loc
buffer[tag] = value;
idxFirst = idxEnd;
}
return buffer;
}
public static void AppendSpecializations(string text, List<string> list=null)
public static void AppendSpecializations(string text, List<string> list = null)
{
if (text == null)
return;
@@ -184,14 +185,14 @@ namespace I2.Loc
list.Add("Any");
var idxFirst = 0;
while (idxFirst<text.Length)
while (idxFirst < text.Length)
{
idxFirst = text.IndexOf("[i2s_", idxFirst, StringComparison.Ordinal);
if (idxFirst < 0)
break;
idxFirst += "[i2s_".Length;
int idx = text.IndexOf(']', idxFirst);
var idx = text.IndexOf(']', idxFirst);
if (idx < 0)
break;

View File

@@ -1,19 +1,19 @@
{
"name": "I2.Editor",
"rootNamespace": "",
"references": [
"GUID:a031cbf5ca7656a4183ccaf405b762ef",
"GUID:6055be8ebefd69e48b49212b09b47b2f"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
"name": "I2.Editor",
"rootNamespace": "",
"references": [
"GUID:a031cbf5ca7656a4183ccaf405b762ef",
"GUID:6055be8ebefd69e48b49212b09b47b2f"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -5,130 +5,208 @@ using UnityEngine;
namespace I2.Loc
{
public partial class LocalizationEditor
{
#region Variables
private List<string> mTranslationTerms = new List<string>();
private Dictionary<string, TranslationQuery> mTranslationRequests = new Dictionary<string, TranslationQuery> ();
private bool mAppNameTerm_Expanded;
public partial class LocalizationEditor
{
private void OnGUI_Languages()
{
//GUILayout.Space(5);
private List<string> mLanguageCodePopupList;
OnGUI_ShowMsg();
#endregion
void OnGUI_Languages()
{
//GUILayout.Space(5);
OnGUI_ShowMsg();
OnGUI_LanguageList();
OnGUI_LanguageList();
OnGUI_StoreIntegration();
GUILayout.BeginHorizontal();
GUILayout.Label(new GUIContent("On Missing Translation:", "What should happen IN-GAME when a term is not yet translated to the current language?"), EditorStyles.boldLabel, GUILayout.Width(200));
GUILayout.BeginVertical();
GUILayout.Space(7);
EditorGUILayout.PropertyField(mProp_OnMissingTranslation, GUITools.EmptyContent, GUILayout.Width(165));
GUILayout.EndVertical();
GUILayout.Label(
new GUIContent("On Missing Translation:",
"What should happen IN-GAME when a term is not yet translated to the current language?"),
EditorStyles.boldLabel, GUILayout.Width(200));
GUILayout.BeginVertical();
GUILayout.Space(7);
EditorGUILayout.PropertyField(mProp_OnMissingTranslation, GUITools.EmptyContent, GUILayout.Width(165));
GUILayout.EndVertical();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label(new GUIContent("Unload Languages At Runtime:", "When playing the game, the plugin will unload all unused languages and only load them when needed"), EditorStyles.boldLabel, GUILayout.Width(200));
GUILayout.BeginVertical();
GUILayout.Space(7);
EditorGUILayout.PropertyField(mProp_AllowUnloadingLanguages, GUITools.EmptyContent, GUILayout.Width(165));
GUILayout.EndVertical();
GUILayout.Label(
new GUIContent("Unload Languages At Runtime:",
"When playing the game, the plugin will unload all unused languages and only load them when needed"),
EditorStyles.boldLabel, GUILayout.Width(200));
GUILayout.BeginVertical();
GUILayout.Space(7);
EditorGUILayout.PropertyField(mProp_AllowUnloadingLanguages, GUITools.EmptyContent, GUILayout.Width(165));
GUILayout.EndVertical();
GUILayout.EndHorizontal();
var firstLanguage = "";
if (mLanguageSource.mLanguages.Count > 0)
firstLanguage = " (" + mLanguageSource.mLanguages[0].Name + ")";
string firstLanguage = "";
if (mLanguageSource.mLanguages.Count > 0)
firstLanguage = " (" + mLanguageSource.mLanguages [0].Name + ")";
GUILayout.BeginHorizontal();
GUILayout.Label(new GUIContent("Default Language:", "When the game starts this is the language that will be used until the player manually selects a language"), EditorStyles.boldLabel, GUILayout.Width(160));
GUILayout.BeginVertical();
GUILayout.Space(7);
GUILayout.BeginHorizontal();
GUILayout.Label(
new GUIContent("Default Language:",
"When the game starts this is the language that will be used until the player manually selects a language"),
EditorStyles.boldLabel, GUILayout.Width(160));
GUILayout.BeginVertical();
GUILayout.Space(7);
mProp_IgnoreDeviceLanguage.boolValue = EditorGUILayout.Popup(mProp_IgnoreDeviceLanguage.boolValue?1:0, new[]{"Device Language", "First in List"+firstLanguage}, GUILayout.ExpandWidth(true))==1;
GUILayout.EndVertical();
GUILayout.EndHorizontal();
mProp_IgnoreDeviceLanguage.boolValue = EditorGUILayout.Popup(mProp_IgnoreDeviceLanguage.boolValue ? 1 : 0,
new[] { "Device Language", "First in List" + firstLanguage }, GUILayout.ExpandWidth(true)) == 1;
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
#region Store Integration
private void OnGUI_StoreIntegration()
{
var lstyle = new GUIStyle(EditorStyles.label);
lstyle.richText = true;
GUILayout.BeginHorizontal();
GUILayout.Label(
new GUIContent("Store Integration:",
"Setups the stores to detect that the game has localization, Android adds strings.xml for each language. IOS modifies the Info.plist"),
EditorStyles.boldLabel, GUILayout.Width(160));
GUILayout.FlexibleSpace();
GUILayout.Label(
new GUIContent("<color=green><size=16>\u2713</size></color> IOS",
"Setups the stores to show in iTunes and the Appstore all the languages that this app supports, also localizes the app name if available"),
lstyle, GUILayout.Width(90));
GUILayout.Label(
new GUIContent("<color=green><size=16>\u2713</size></color> Android",
"Setups the stores to show in GooglePlay all the languages this app supports, also localizes the app name if available"),
lstyle, GUILayout.Width(90));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
mAppNameTerm_Expanded = GUILayout.Toggle(mAppNameTerm_Expanded,
new GUIContent("App Name translations:",
"How should the game be named in the devices based on their language"), EditorStyles.foldout,
GUILayout.Width(160));
GUILayout.Label("", GUILayout.ExpandWidth(true));
var rect = GUILayoutUtility.GetLastRect();
TermsPopup_Drawer.ShowGUI(rect, mProp_AppNameTerm, GUITools.EmptyContent, mLanguageSource);
if (GUILayout.Button("New Term", EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
{
AddLocalTerm("App_Name");
mProp_AppNameTerm.stringValue = "App_Name";
mAppNameTerm_Expanded = true;
}
GUILayout.EndHorizontal();
if (mAppNameTerm_Expanded)
{
GUILayout.BeginHorizontal();
GUILayout.Space(10);
GUILayout.BeginVertical("Box");
var termName = mProp_AppNameTerm.stringValue;
if (!string.IsNullOrEmpty(termName))
{
var termData = LocalizationManager.GetTermData(termName);
if (termData != null)
OnGUI_Keys_Languages(mProp_AppNameTerm.stringValue, ref termData, null, true, mLanguageSource);
}
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUILayout.Label("<b>Default App Name:</b>", lstyle, GUITools.DontExpandWidth);
GUILayout.Label(Application.productName);
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
}
#endregion
#region Variables
private readonly List<string> mTranslationTerms = new();
private readonly Dictionary<string, TranslationQuery> mTranslationRequests = new();
private bool mAppNameTerm_Expanded;
private List<string> mLanguageCodePopupList;
#endregion
#region GUI Languages
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 ]--------------------------
private 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();
int IndexLanguageToDelete = -1;
int LanguageToMoveUp = -1;
int LanguageToMoveDown = -1;
//--[ Language List ]--------------------------
var IndexLanguageToDelete = -1;
var LanguageToMoveUp = -1;
var 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));
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)
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;
for (int i = 0, imax = mProp_Languages.arraySize; i < imax; ++i)
{
var Prop_Lang = mProp_Languages.GetArrayElementAtIndex(i);
var Prop_LangName = Prop_Lang.FindPropertyRelative("Name");
var Prop_LangCode = Prop_Lang.FindPropertyRelative("Code");
var Prop_Flags = Prop_Lang.FindPropertyRelative("Flags");
var 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);
if (GUILayout.Button("X", "toolbarbutton", GUILayout.ExpandWidth(false))) IndexLanguageToDelete = i;
EditorGUI.BeginChangeCheck();
string LanName = EditorGUILayout.TextField(Prop_LangName.stringValue, GUILayout.ExpandWidth(true));
if (EditorGUI.EndChangeCheck() && !string.IsNullOrEmpty(LanName))
{
Prop_LangName.stringValue = LanName;
}
GUILayout.BeginHorizontal(EditorStyles.toolbar);
EditorGUI.BeginChangeCheck();
var 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)));
var Index = Mathf.Max(0, mLanguageCodePopupList.FindIndex(c => c.Contains(currentCode)));
EditorGUI.BeginChangeCheck();
Index = EditorGUILayout.Popup(Index, mLanguageCodePopupList.ToArray(), EditorStyles.toolbarPopup, GUILayout.Width(60));
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("]");
var i0 = currentCode.IndexOf("[");
var 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);
}
@@ -139,225 +217,236 @@ namespace I2.Loc
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 = i < imax - 1;
if (GUILayout.Button("\u25BC", EditorStyles.toolbarButton, GUILayout.Width(18))) LanguageToMoveDown = i;
GUI.enabled = i > 0;
if (GUILayout.Button("\u25B2", EditorStyles.toolbarButton, GUILayout.Width(18))) LanguageToMoveUp = i;
GUI.enabled = true;
if (GUILayout.Button( new GUIContent("Show", "Preview all localizations into this language"), EditorStyles.toolbarButton, GUILayout.Width(35)))
{
LocalizationManager.SetLanguageAndCode( LanName, Prop_LangCode.stringValue, false, true);
}
if (GUILayout.Button(new GUIContent("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;
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));
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"));
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
var time = (int)(Time.realtimeSinceStartup % 2 * 2.5);
var 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)))
{
Prop_Flags.intValue = (Prop_Flags.intValue & ~(int)eLanguageDataFlags.DISABLED) | (isLanguageEnabled ? 0 : (int)eLanguageDataFlags.DISABLED);
GoogleTranslation.CancelCurrentGoogleTranslations();
StopConnectionWWW();
}
GUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
OnGUI_AddLanguage( mProp_Languages );
Repaint();
}
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)))
if (IndexLanguageToDelete >= 0)
if (EditorUtility.DisplayDialog("Confirm delete",
"Are you sure you want to delete the selected language", "Yes", "Cancel"))
{
GoogleTranslation.CancelCurrentGoogleTranslations ();
StopConnectionWWW();
mLanguageSource.RemoveLanguage(mLanguageSource.mLanguages[IndexLanguageToDelete].Name);
serializedObject.Update();
ParseTerms(true, false, false);
}
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 );
}
if (LanguageToMoveUp >= 0) SwapLanguages(LanguageToMoveUp, LanguageToMoveUp - 1);
if (LanguageToMoveDown >= 0) SwapLanguages(LanguageToMoveDown, LanguageToMoveDown + 1);
}
void SwapLanguages( int iFirst, int iSecond )
{
serializedObject.ApplyModifiedProperties();
LanguageSourceData Source = mLanguageSource;
private void SwapLanguages(int iFirst, int iSecond)
{
serializedObject.ApplyModifiedProperties();
var Source = mLanguageSource;
SwapValues( Source.mLanguages, iFirst, iSecond );
foreach (TermData termData in Source.mTerms)
{
SwapValues ( termData.Languages, iFirst, iSecond );
SwapValues ( termData.Flags, iFirst, iSecond );
}
serializedObject.Update();
}
SwapValues(Source.mLanguages, iFirst, iSecond);
foreach (var termData in Source.mTerms)
{
SwapValues(termData.Languages, iFirst, iSecond);
SwapValues(termData.Flags, iFirst, iSecond);
}
void SwapValues( List<LanguageData> mList, int Index1, int Index2 )
{
LanguageData temp = mList[Index1];
mList[Index1] = mList[Index2];
mList[Index2] = temp;
}
void SwapValues( string[] mList, int Index1, int Index2 )
{
string temp = mList[Index1];
mList[Index1] = mList[Index2];
mList[Index2] = temp;
}
void SwapValues( byte[] mList, int Index1, int Index2 )
{
byte temp = mList[Index1];
mList[Index1] = mList[Index2];
mList[Index2] = temp;
}
serializedObject.Update();
}
void OnGUI_AddLanguage( SerializedProperty Prop_Languages)
{
private void SwapValues(List<LanguageData> mList, int Index1, int Index2)
{
var temp = mList[Index1];
mList[Index1] = mList[Index2];
mList[Index2] = temp;
}
private void SwapValues(string[] mList, int Index1, int Index2)
{
var temp = mList[Index1];
mList[Index1] = mList[Index2];
mList[Index2] = temp;
}
private void SwapValues(byte[] mList, int Index1, int Index2)
{
var temp = mList[Index1];
mList[Index1] = mList[Index2];
mList[Index2] = temp;
}
private void OnGUI_AddLanguage(SerializedProperty Prop_Languages)
{
//--[ Add Language Upper Toolbar ]-----------------
GUILayout.BeginVertical();
GUILayout.BeginHorizontal();
GUILayout.BeginHorizontal(EditorStyles.toolbar);
mLanguages_NewLanguage = EditorGUILayout.TextField("", mLanguages_NewLanguage, EditorStyles.toolbarTextField, GUILayout.ExpandWidth(true));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUI.enabled = !string.IsNullOrEmpty (mLanguages_NewLanguage);
if (TestButton(eTest_ActionType.Button_AddLanguageManual,"Add", EditorStyles.toolbarButton, GUILayout.Width(50)))
{
Prop_Languages.serializedObject.ApplyModifiedProperties();
mLanguageSource.AddLanguage( mLanguages_NewLanguage, GoogleLanguages.GetLanguageCode(mLanguages_NewLanguage) );
Prop_Languages.serializedObject.Update();
mLanguages_NewLanguage = "";
GUILayout.BeginHorizontal(EditorStyles.toolbar);
mLanguages_NewLanguage = EditorGUILayout.TextField("", mLanguages_NewLanguage,
EditorStyles.toolbarTextField, GUILayout.ExpandWidth(true));
GUILayout.EndHorizontal();
GUI.enabled = !string.IsNullOrEmpty(mLanguages_NewLanguage);
if (TestButton(eTest_ActionType.Button_AddLanguageManual, "Add", EditorStyles.toolbarButton,
GUILayout.Width(50)))
{
Prop_Languages.serializedObject.ApplyModifiedProperties();
mLanguageSource.AddLanguage(mLanguages_NewLanguage,
GoogleLanguages.GetLanguageCode(mLanguages_NewLanguage));
Prop_Languages.serializedObject.Update();
mLanguages_NewLanguage = "";
GUI.FocusControl(string.Empty);
}
GUI.enabled = true;
GUILayout.EndHorizontal();
GUILayout.EndHorizontal();
//--[ Add Language Bottom Toolbar ]-----------------
GUILayout.BeginHorizontal();
//-- Language Dropdown -----------------
string CodesToExclude = string.Empty;
foreach (var LanData in mLanguageSource.mLanguages)
CodesToExclude = string.Concat(CodesToExclude, "[", LanData.Code, "]");
GUILayout.BeginHorizontal();
List<string> Languages = GoogleLanguages.GetLanguagesForDropdown(mLanguages_NewLanguage, CodesToExclude);
//-- Language Dropdown -----------------
var CodesToExclude = string.Empty;
foreach (var LanData in mLanguageSource.mLanguages)
CodesToExclude = string.Concat(CodesToExclude, "[", LanData.Code, "]");
GUI.changed = false;
int index = EditorGUILayout.Popup(0, Languages.ToArray(), EditorStyles.toolbarDropDown);
var Languages = GoogleLanguages.GetLanguagesForDropdown(mLanguages_NewLanguage, CodesToExclude);
if (GUI.changed && index>=0)
{
mLanguages_NewLanguage = GoogleLanguages.GetFormatedLanguageName( Languages[index] );
}
if (TestButton(eTest_ActionType.Button_AddLanguageFromPopup, "Add", EditorStyles.toolbarButton, GUILayout.Width(50)) && index>=0)
{
GUI.changed = false;
var index = EditorGUILayout.Popup(0, Languages.ToArray(), EditorStyles.toolbarDropDown);
if (GUI.changed && index >= 0)
mLanguages_NewLanguage = GoogleLanguages.GetFormatedLanguageName(Languages[index]);
if (TestButton(eTest_ActionType.Button_AddLanguageFromPopup, "Add", EditorStyles.toolbarButton,
GUILayout.Width(50)) && index >= 0)
{
Prop_Languages.serializedObject.ApplyModifiedProperties();
mLanguages_NewLanguage = GoogleLanguages.GetFormatedLanguageName(Languages[index]);
if (!string.IsNullOrEmpty(mLanguages_NewLanguage))
mLanguageSource.AddLanguage(mLanguages_NewLanguage, GoogleLanguages.GetLanguageCode(mLanguages_NewLanguage));
mLanguageSource.AddLanguage(mLanguages_NewLanguage,
GoogleLanguages.GetLanguageCode(mLanguages_NewLanguage));
Prop_Languages.serializedObject.Update();
mLanguages_NewLanguage = "";
GUI.FocusControl(string.Empty);
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUI.color = Color.white;
}
GUILayout.EndVertical();
GUI.color = Color.white;
}
void TranslateAllToLanguage (string lanName)
{
if (!GoogleTranslation.CanTranslate ())
{
ShowError ("WebService is not set correctly or needs to be reinstalled");
return;
}
private 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);
var LanIndex = mLanguageSource.GetLanguageIndex(lanName);
var code = mLanguageSource.mLanguages[LanIndex].Code;
var 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)
{
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 );
if (!string.IsNullOrEmpty(termData.Languages[LanIndex]))
continue;
mTranslationTerms.Add (termData.Term);
string sourceCode, sourceText;
FindTranslationSource(LanguageSourceData.GetKeyFromFullTerm(termData.Term), termData, code, null,
out sourceText, out sourceCode);
GoogleTranslation.CreateQueries(sourceText, sourceCode, googleCode, mTranslationRequests); // can split plurals into several queries
}
mTranslationTerms.Add(termData.Term);
if (mTranslationRequests.Count == 0)
{
StopConnectionWWW ();
return;
}
GoogleTranslation.CreateQueries(sourceText, sourceCode, googleCode,
mTranslationRequests); // can split plurals into several queries
}
mConnection_WWW = null;
mConnection_Text = "Translating"; if (mTranslationRequests.Count > 1) mConnection_Text += " (" + mTranslationRequests.Count + ")";
mConnection_Callback = null;
//EditorApplication.update += CheckForConnection;
if (mTranslationRequests.Count == 0)
{
StopConnectionWWW();
return;
}
GoogleTranslation.Translate (mTranslationRequests, OnLanguageTranslated);
}
mConnection_WWW = null;
mConnection_Text = "Translating";
if (mTranslationRequests.Count > 1) mConnection_Text += " (" + mTranslationRequests.Count + ")";
mConnection_Callback = null;
//EditorApplication.update += CheckForConnection;
void OnLanguageTranslated( Dictionary<string, TranslationQuery> requests, string Error )
{
//Debug.Log (Result);
GoogleTranslation.Translate(mTranslationRequests, OnLanguageTranslated);
}
private void OnLanguageTranslated(Dictionary<string, TranslationQuery> requests, string Error)
{
//Debug.Log (Result);
//if (Result.Contains("Service invoked too many times"))
//{
@@ -367,28 +456,28 @@ namespace I2.Loc
// return;
//}
//if (!string.IsNullOrEmpty(Error))/* || !Result.Contains("<i2>")*/
//{
//if (!string.IsNullOrEmpty(Error))/* || !Result.Contains("<i2>")*/
//{
// Debug.LogError("WEB ERROR: " + Error);
// ShowError ("Unable to access Google or not valid request");
// return;
//}
// ShowError ("Unable to access Google or not valid request");
// return;
//}
ClearErrors();
ClearErrors();
StopConnectionWWW();
if (!string.IsNullOrEmpty(Error))
{
ShowError (Error);
{
ShowError(Error);
return;
}
}
if (requests.Values.Count == 0)
return;
var langCode = requests.Values.First().TargetLanguagesCode [0];
if (requests.Values.Count == 0)
return;
var langCode = requests.Values.First().TargetLanguagesCode[0];
//langCode = GoogleLanguages.GetGoogleLanguageCode(langCode);
int langIndex = mLanguageSource.GetLanguageIndexFromCode (langCode, false);
var langIndex = mLanguageSource.GetLanguageIndexFromCode(langCode, false);
//if (langIndex >= 0)
{
foreach (var term in mTranslationTerms)
@@ -399,79 +488,25 @@ namespace I2.Loc
if (termData.TermType != eTermType.Text)
continue;
//if (termData.Languages.Length <= langIndex)
// continue;
// continue;
string sourceCode, sourceText;
FindTranslationSource(LanguageSourceData.GetKeyFromFullTerm(termData.Term), termData, langCode, null, out sourceText, out sourceCode);
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
var 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 ();
}
mTranslationTerms.Clear();
mTranslationRequests.Clear();
StopConnectionWWW();
}
#endregion
#region Store Integration
void OnGUI_StoreIntegration()
{
GUIStyle lstyle = new GUIStyle (EditorStyles.label);
lstyle.richText = true;
GUILayout.BeginHorizontal ();
GUILayout.Label (new GUIContent("Store Integration:", "Setups the stores to detect that the game has localization, Android adds strings.xml for each language. IOS modifies the Info.plist"), EditorStyles.boldLabel, GUILayout.Width(160));
GUILayout.FlexibleSpace();
GUILayout.Label( new GUIContent( "<color=green><size=16>\u2713</size></color> IOS", "Setups the stores to show in iTunes and the Appstore all the languages that this app supports, also localizes the app name if available" ), lstyle, GUILayout.Width( 90 ) );
GUILayout.Label( new GUIContent( "<color=green><size=16>\u2713</size></color> Android", "Setups the stores to show in GooglePlay all the languages this app supports, also localizes the app name if available" ), lstyle, GUILayout.Width( 90 ) );
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal();
mAppNameTerm_Expanded = GUILayout.Toggle(mAppNameTerm_Expanded, new GUIContent( "App Name translations:", "How should the game be named in the devices based on their language" ), EditorStyles.foldout, GUILayout.Width( 160 ) );
GUILayout.Label("", GUILayout.ExpandWidth(true));
var rect = GUILayoutUtility.GetLastRect();
TermsPopup_Drawer.ShowGUI( rect, mProp_AppNameTerm, GUITools.EmptyContent, mLanguageSource);
if (GUILayout.Button("New Term", EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
{
AddLocalTerm("App_Name");
mProp_AppNameTerm.stringValue = "App_Name";
mAppNameTerm_Expanded = true;
}
GUILayout.EndHorizontal();
if (mAppNameTerm_Expanded)
{
GUILayout.BeginHorizontal();
GUILayout.Space(10);
GUILayout.BeginVertical("Box");
var termName = mProp_AppNameTerm.stringValue;
if (!string.IsNullOrEmpty(termName))
{
var termData = LocalizationManager.GetTermData(termName);
if (termData != null)
OnGUI_Keys_Languages(mProp_AppNameTerm.stringValue, ref termData, null, true, mLanguageSource);
}
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUILayout.Label("<b>Default App Name:</b>", lstyle, GUITools.DontExpandWidth);
GUILayout.Label(Application.productName);
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
}
#endregion
}
#endregion
}
}

View File

@@ -5,16 +5,18 @@ using UnityEngine;
namespace I2.Loc
{
public partial class LocalizationEditor
{
void OnGUI_Warning_SourceInScene()
{
public partial class LocalizationEditor
{
private bool bSourceInsidePluginsFolder = true;
private void OnGUI_Warning_SourceInScene()
{
// if (mLanguageSource.UserAgreesToHaveItOnTheScene) return;
// LanguageSourceData source = GetSourceData();
// if (source.IsGlobalSource() && !GUITools.ObjectExistInScene(source.gameObject))
// return;
// string Text = @"Its advised to only use the source in I2\Localization\Resources\I2Languages.prefab
//That works as a GLOBAL source accessible in ALL scenes. Thats why its recommended to add all your translations there.
@@ -26,7 +28,7 @@ namespace I2.Loc
//Furthermore, having a source in the scene require that any Localize component get a reference to that source to work properly. By dragging the source into the field at the bottom of the Localize component.";
// EditorGUILayout.HelpBox(Text, MessageType.Warning);
// GUILayout.BeginHorizontal();
// GUILayout.FlexibleSpace();
// if (GUILayout.Button("Keep as is"))
@@ -34,15 +36,15 @@ namespace I2.Loc
// SerializedProperty Agree = serializedObject.FindProperty("UserAgreesToHaveItOnTheScene");
// Agree.boolValue = true;
// }
// GUILayout.FlexibleSpace();
// if (GUILayout.Button("Open the Global Source"))
// {
// GameObject Prefab = (Resources.Load(LocalizationManager.GlobalSources[0]) as GameObject);
// Selection.activeGameObject = Prefab;
// }
// GUILayout.FlexibleSpace();
// if (GUILayout.Button("Delete this and open the Global Source"))
// {
@@ -68,106 +70,100 @@ namespace I2.Loc
// }
// GUILayout.FlexibleSpace();
// GUILayout.EndHorizontal();
// GUILayout.Space(10);
}
}
private bool bSourceInsidePluginsFolder = true;
public void OnGUI_Warning_SourceInsidePluginsFolder()
{
if (!bSourceInsidePluginsFolder || mLanguageSource.UserAgreesToHaveItInsideThePluginsFolder)
return;
if (!mLanguageSource.IsGlobalSource())
{
bSourceInsidePluginsFolder = false;
return;
}
public void OnGUI_Warning_SourceInsidePluginsFolder()
{
if (!bSourceInsidePluginsFolder || mLanguageSource.UserAgreesToHaveItInsideThePluginsFolder)
return;
string pluginPath = UpgradeManager.GetI2LocalizationPath();
string assetPath = AssetDatabase.GetAssetPath(target);
if (!mLanguageSource.IsGlobalSource())
{
bSourceInsidePluginsFolder = false;
return;
}
if (!assetPath.StartsWith(pluginPath, StringComparison.OrdinalIgnoreCase))
{
bSourceInsidePluginsFolder = false;
return;
}
string Text = @"Its advised to move this Global Source to a folder outside the I2 Localization.
var pluginPath = UpgradeManager.GetI2LocalizationPath();
var assetPath = AssetDatabase.GetAssetPath(target);
if (!assetPath.StartsWith(pluginPath, StringComparison.OrdinalIgnoreCase))
{
bSourceInsidePluginsFolder = false;
return;
}
var Text = @"Its advised to move this Global Source to a folder outside the I2 Localization.
For example (Assets/I2/Resources) instead of (Assets/I2/Localization/Resources)
That way upgrading the plugin its as easy as deleting the I2/Localization and I2/Common folders and reinstalling.
Do you want the plugin to automatically move the LanguageSource to a folder outside the plugin?";
EditorGUILayout.HelpBox(Text, MessageType.Warning);
EditorGUILayout.HelpBox(Text, MessageType.Warning);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Keep as is"))
{
SerializedProperty Agree = serializedObject.FindProperty("UserAgreesToHaveItInsideThePluginsFolder");
Agree.boolValue = true;
bSourceInsidePluginsFolder = true;
}
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Keep as is"))
{
var Agree = serializedObject.FindProperty("UserAgreesToHaveItInsideThePluginsFolder");
Agree.boolValue = true;
bSourceInsidePluginsFolder = true;
}
GUILayout.FlexibleSpace();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Ask me later"))
{
bSourceInsidePluginsFolder = false;
}
if (GUILayout.Button("Ask me later")) bSourceInsidePluginsFolder = false;
GUILayout.FlexibleSpace();
if (GUILayout.Button("Move to the Recommended Folder"))
EditorApplication.delayCall += MoveGlobalSource;
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Move to the Recommended Folder"))
EditorApplication.delayCall += MoveGlobalSource;
GUILayout.Space(10);
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(10);
}
public bool OnGUI_Warning_SourceNotUpToDate()
{
if (mProp_GoogleLiveSyncIsUptoDate.boolValue)
{
return false;
}
if (mProp_GoogleLiveSyncIsUptoDate.boolValue) return false;
string Text = "Spreadsheet is not up-to-date and Google Live Synchronization is enabled\n\nWhen playing in the device the Spreadsheet will be downloaded and override the translations built from the editor.\n\nTo fix this, Import or Export REPLACE to Google";
var Text =
"Spreadsheet is not up-to-date and Google Live Synchronization is enabled\n\nWhen playing in the device the Spreadsheet will be downloaded and override the translations built from the editor.\n\nTo fix this, Import or Export REPLACE to Google";
EditorGUILayout.HelpBox(Text, MessageType.Warning);
return true;
}
private static void MoveGlobalSource()
{
EditorApplication.delayCall -= MoveGlobalSource;
private static void MoveGlobalSource()
{
EditorApplication.delayCall -= MoveGlobalSource;
string pluginPath = UpgradeManager.GetI2LocalizationPath();
string assetPath = AssetDatabase.GetAssetPath(mLanguageSource.ownerObject);
var pluginPath = UpgradeManager.GetI2LocalizationPath();
var assetPath = AssetDatabase.GetAssetPath(mLanguageSource.ownerObject);
string I2Path = pluginPath.Substring(0, pluginPath.Length-"/Localization".Length);
string newPath = I2Path + "/Resources/" + mLanguageSource.ownerObject.name + ".prefab";
var I2Path = pluginPath.Substring(0, pluginPath.Length - "/Localization".Length);
var newPath = I2Path + "/Resources/" + mLanguageSource.ownerObject.name + ".prefab";
string fullresFolder = Application.dataPath + I2Path.Replace("Assets","") + "/Resources";
bool folderExists = Directory.Exists (fullresFolder);
if (!folderExists)
AssetDatabase.CreateFolder(I2Path, "Resources");
AssetDatabase.MoveAsset(assetPath, newPath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
var fullresFolder = Application.dataPath + I2Path.Replace("Assets", "") + "/Resources";
var folderExists = Directory.Exists(fullresFolder);
var prefab = AssetDatabase.LoadAssetAtPath(newPath, typeof(GameObject)) as GameObject;
Selection.activeGameObject = prefab;
if (!folderExists)
AssetDatabase.CreateFolder(I2Path, "Resources");
AssetDatabase.MoveAsset(assetPath, newPath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
Debug.Log("LanguageSource moved to:" + newPath);
ShowInfo("Please, ignore some console warnings/errors produced by this operation, everything worked fine. In a new release those warnings will be cleared");
}
var prefab = AssetDatabase.LoadAssetAtPath(newPath, typeof(GameObject)) as GameObject;
Selection.activeGameObject = prefab;
public static void DelayedDestroySource()
{
Debug.Log("LanguageSource moved to:" + newPath);
ShowInfo(
"Please, ignore some console warnings/errors produced by this operation, everything worked fine. In a new release those warnings will be cleared");
}
}
}
public static void DelayedDestroySource()
{
}
}
}

View File

@@ -57,11 +57,12 @@ namespace I2.Loc
LocalizationManager.UpdateSources();
// Get language with variants, but also add it without the variant to allow fallbacks (e.g. en-CA also adds en)
var langCodes = LocalizationManager.GetAllLanguagesCode(false).Concat( LocalizationManager.GetAllLanguagesCode(true) ).Distinct().ToList();
var langCodes =
LocalizationManager.GetAllLanguagesCode(false).Concat( LocalizationManager.GetAllLanguagesCode(true) ).Distinct().ToList();
if (langCodes.Count <= 0)
return;
string stringXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
string stringXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
"<resources>\n"+
" <string name=\"app_name\">{0}</string>\n"+
"</resources>";
@@ -109,7 +110,8 @@ namespace I2.Loc
{
try
{
appName = appName.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "\\\"").Replace("'", "\\'");
appName =
appName.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "\\\"").Replace("'", "\\'");
appName = appName.Replace("\r\n", string.Empty).Replace("\n", string.Empty).Replace("\r", string.Empty);
if (!System.IO.Directory.Exists(folder))
@@ -129,14 +131,16 @@ namespace I2.Loc
if (regexPattern.IsMatch(stringXML))
{
// Override the AppName if it was found
stringXML = regexPattern.Replace(stringXML, string.Format("\"app_name\">{0}</string>", appName));
stringXML =
regexPattern.Replace(stringXML, string.Format("\"app_name\">{0}</string>", appName));
}
else
{
// insert the appName if it wasn't there
int idx = stringXML.IndexOf("<resources>");
if (idx > 0)
stringXML = stringXML.Insert(idx + "</resources>".Length, string.Format("\n <string name=\"app_name\">{0}</string>\n", appName));
stringXML =
stringXML.Insert(idx + "</resources>".Length, string.Format("\n <string name=\"app_name\">{0}</string>\n", appName));
}
}
System.IO.File.WriteAllText(folder + "/" + fileName, stringXML);

View File

@@ -1,55 +1,50 @@
using System;
using System.Linq;
using UnityEngine;
using Object = UnityEngine.Object;
namespace I2.Loc
{
public partial class LanguageSourceData
{
public partial class LanguageSourceData
{
#region Assets
public void UpdateAssetDictionary()
{
Assets.RemoveAll(x => x == null);
mAssetDictionary = Assets.Distinct()
.GroupBy(o => o.name, System.StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First(), System.StringComparer.Ordinal);
.GroupBy(o => o.name, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal);
}
public Object FindAsset( string Name )
{
if (Assets!=null)
{
if (mAssetDictionary==null || mAssetDictionary.Count!=Assets.Count)
{
UpdateAssetDictionary();
}
public Object FindAsset(string Name)
{
if (Assets != null)
{
if (mAssetDictionary == null || mAssetDictionary.Count != Assets.Count) UpdateAssetDictionary();
Object obj;
if (mAssetDictionary.TryGetValue(Name, out obj))
{
return obj;
}
//for (int i=0, imax=Assets.Length; i<imax; ++i)
// if (Assets[i]!=null && Name.EndsWith( Assets[i].name, StringComparison.OrdinalIgnoreCase))
// return Assets[i];
}
return null;
}
public bool HasAsset( Object Obj )
{
return Assets.Contains(Obj);
}
if (mAssetDictionary.TryGetValue(Name, out obj)) return obj;
//for (int i=0, imax=Assets.Length; i<imax; ++i)
// if (Assets[i]!=null && Name.EndsWith( Assets[i].name, StringComparison.OrdinalIgnoreCase))
// return Assets[i];
}
public void AddAsset( Object Obj )
{
return null;
}
public bool HasAsset(Object Obj)
{
return Assets.Contains(Obj);
}
public void AddAsset(Object Obj)
{
if (Assets.Contains(Obj))
return;
Assets.Add(Obj);
UpdateAssetDictionary();
}
}
#endregion
}
#endregion
}
}

View File

@@ -42,7 +42,8 @@ namespace I2.Loc
#region I2CSV format
public string Export_I2CSV(string Category, char Separator = ',', bool specializationsAsRows = true, bool sortRows=true)
public string Export_I2CSV(string Category, char Separator = ',', bool specializationsAsRows = true,
bool sortRows = true)
{
var Builder = new StringBuilder();
@@ -58,10 +59,7 @@ namespace I2.Loc
Builder.Append("[ln]");
if (sortRows)
{
mTerms.Sort((a, b) => string.CompareOrdinal(a.Term, b.Term));
}
if (sortRows) mTerms.Sort((a, b) => string.CompareOrdinal(a.Term, b.Term));
var nLanguages = mLanguages.Count;
var firstLine = true;
@@ -70,7 +68,7 @@ namespace I2.Loc
string Term;
if (string.IsNullOrEmpty(Category) ||
Category == EmptyCategory && termData.Term.IndexOfAny(CategorySeparators) < 0)
(Category == EmptyCategory && termData.Term.IndexOfAny(CategorySeparators) < 0))
Term = termData.Term;
else if (termData.Term.StartsWith(Category + @"/", StringComparison.Ordinal) &&
Category != termData.Term)
@@ -136,7 +134,7 @@ namespace I2.Loc
translation = string.Empty;
else
if (translation == "")
translation = "-";*/
translation = "-";*/
//if (isAutoTranslated) Builder.Append("[i2auto]");
AppendI2Text(Builder, translation);
}
@@ -156,7 +154,8 @@ namespace I2.Loc
#region CSV format
public string Export_CSV(string Category, char Separator = ',', bool specializationsAsRows = true, bool sortRows=true)
public string Export_CSV(string Category, char Separator = ',', bool specializationsAsRows = true,
bool sortRows = true)
{
var Builder = new StringBuilder();
@@ -174,17 +173,14 @@ namespace I2.Loc
Builder.Append("\n");
if (sortRows)
{
mTerms.Sort((a, b) => string.CompareOrdinal(a.Term, b.Term));
}
if (sortRows) mTerms.Sort((a, b) => string.CompareOrdinal(a.Term, b.Term));
foreach (var termData in mTerms)
{
string Term;
if (string.IsNullOrEmpty(Category) ||
Category == EmptyCategory && termData.Term.IndexOfAny(CategorySeparators) < 0)
(Category == EmptyCategory && termData.Term.IndexOfAny(CategorySeparators) < 0))
Term = termData.Term;
else if (termData.Term.StartsWith(Category + @"/", StringComparison.Ordinal) &&
Category != termData.Term)

View File

@@ -16,253 +16,14 @@ namespace I2.Loc
[AddComponentMenu("I2/Localization/I2 Localize")]
public class Localize : MonoBehaviour
{
#region Variables: Term
public string Term
#region Finding Target
public bool FindTarget()
{
get { return mTerm; }
set { SetTerm(value); }
}
public string SecondaryTerm
{
get { return mTermSecondary; }
set { SetTerm(null, value); }
}
public string mTerm = string.Empty, // if Target is a Label, this will be the text, if sprite, this will be the spriteName, etc
mTermSecondary = string.Empty; // if Target is a Label, this will be the font Name, if sprite, this will be the Atlas name, etc
// 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)
// This are set when the component starts
[NonSerialized] public string FinalTerm, FinalSecondaryTerm;
public enum TermModification { DontModify, ToUpper, ToLower, ToUpperFirst, ToTitle/*, CustomRange*/}
public TermModification PrimaryTermModifier = TermModification.DontModify,
SecondaryTermModifier = TermModification.DontModify;
public string TermPrefix, TermSuffix;
public bool LocalizeOnAwake = true;
string LastLocalizedLanguage; // Used to avoid Localizing everytime the object is Enabled
#if UNITY_EDITOR
public ILanguageSource Source; // Source used while in the Editor to preview the Terms (can be of type LanguageSource or LanguageSourceAsset)
#endif
#endregion
#region Variables: Target
public bool IgnoreRTL; // If false, no Right To Left processing will be done
public int MaxCharactersInRTL; // If the language is RTL, the translation will be split in lines not longer than this amount and the RTL fix will be applied per line
public bool IgnoreNumbersInRTL = true; // If the language is RTL, the translation will not convert numbers (will preserve them like: e.g. 123)
public bool CorrectAlignmentForRTL = true; // If true, when Right To Left language, alignment will be set to Right
public bool AddSpacesToJoinedLanguages; // Some languages (e.g. Chinese, Japanese and Thai) don't add spaces to their words (all characters are placed toguether), making this variable true, will add spaces to all characters to allow wrapping long texts into multiple lines.
public bool AllowLocalizedParameters=true;
public bool AllowParameters=true;
#endregion
#region Variables: References
public List<Object> TranslatedObjects = new List<Object>(); // For targets that reference objects (e.g. AudioSource, UITexture,etc)
// this keeps a reference to the possible options.
// If the value is not the name of any of this objects then it will try to load the object from the Resources
[NonSerialized] public Dictionary<string, Object> mAssetDictionary = new Dictionary<string, Object>(StringComparer.Ordinal); //This is used to overcome the issue with Unity not serializing Dictionaries
#endregion
#region Variable Translation Modifiers
public UnityEvent LocalizeEvent = new UnityEvent(); // This allows scripts to modify the translations : e.g. "Player {0} wins" -> "Player Red wins"
public static string MainTranslation, SecondaryTranslation; // The callback should use and modify this variables
public static string CallBackTerm, CallBackSecondaryTerm; // during the callback, this will hold the FinalTerm and FinalSecondary to know what terms are originating the translation
public static Localize CurrentLocalizeComponent; // while in the LocalizeCallBack, this points to the Localize calling the callback
public bool AlwaysForceLocalize; // Force localization when the object gets enabled (useful for callbacks and parameters that change the localization even through the language is the same as in the previous time it was localized)
[SerializeField] public EventCallback LocalizeCallBack = new EventCallback(); //LocalizeCallBack is deprecated. Please use LocalizeEvent instead.
#endregion
#region Variables: Editor Related
public bool mGUI_ShowReferences;
public bool mGUI_ShowTems = true;
public bool mGUI_ShowCallback;
#endregion
#region Variables: Runtime (LocalizeTarget)
public ILocalizeTarget mLocalizeTarget;
public string mLocalizeTargetName; // Used to resolve multiple targets in a prefab
#endregion
#region Localize
void Awake()
{
#if UNITY_EDITOR
if (BuildPipeline.isBuildingPlayer)
return;
#endif
UpdateAssetDictionary();
FindTarget();
if (LocalizeOnAwake)
OnLocalize();
}
#if UNITY_EDITOR
void OnValidate()
{
if (LocalizeCallBack.HasCallback())
{
try
{
var methodInfo = UnityEventBase.GetValidMethodInfo(LocalizeCallBack.Target, LocalizeCallBack.MethodName, Array.Empty<Type>());
if (methodInfo != null)
{
UnityAction methodDelegate = Delegate.CreateDelegate(typeof(UnityAction), LocalizeCallBack.Target, methodInfo, false) as UnityAction;
if (methodDelegate != null)
UnityEventTools.AddPersistentListener(LocalizeEvent, methodDelegate);
}
}
catch(Exception)
{}
LocalizeCallBack.Target = null;
LocalizeCallBack.MethodName = null;
}
}
#endif
void OnEnable()
{
OnLocalize ();
}
public bool HasCallback()
{
if (LocalizeCallBack.HasCallback())
return true;
return LocalizeEvent.GetPersistentEventCount() > 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;
CurrentLocalizeComponent = this;
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;
{
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 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;
}
#endregion
#region Finding Target
public bool FindTarget()
{
if (mLocalizeTarget != null && mLocalizeTarget.IsValid(this))
return true;
if (mLocalizeTarget!=null)
if (mLocalizeTarget != null)
{
DestroyImmediate(mLocalizeTarget);
mLocalizeTarget = null;
@@ -270,18 +31,14 @@ namespace I2.Loc
}
if (!string.IsNullOrEmpty(mLocalizeTargetName))
{
foreach (var desc in LocalizationManager.mLocalizeTargets)
{
if (mLocalizeTargetName == desc.GetTargetType().ToString())
{
if (desc.CanLocalize(this))
mLocalizeTarget = desc.CreateTarget(this);
if (mLocalizeTarget!=null)
if (mLocalizeTarget != null)
return true;
}
}
}
foreach (var desc in LocalizationManager.mLocalizeTargets)
{
@@ -293,25 +50,329 @@ namespace I2.Loc
return true;
}
return false;
}
return false;
}
#endregion
#endregion
#region Finding Term
// 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;
#region Utilities
if (!FindTarget())
return;
// This can be used to set the language when a button is clicked
public void SetGlobalLanguage(string Language)
{
LocalizationManager.CurrentLanguage = Language;
}
#endregion
#region Variables: Term
public string Term
{
get => mTerm;
set => SetTerm(value);
}
public string SecondaryTerm
{
get => mTermSecondary;
set => SetTerm(null, value);
}
public string mTerm =
string.Empty, // if Target is a Label, this will be the text, if sprite, this will be the spriteName, etc
mTermSecondary =
string.Empty; // if Target is a Label, this will be the font Name, if sprite, this will be the Atlas name, etc
// 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)
// This are set when the component starts
[NonSerialized] public string FinalTerm, FinalSecondaryTerm;
public enum TermModification
{
DontModify,
ToUpper,
ToLower,
ToUpperFirst,
ToTitle /*, CustomRange*/
}
public TermModification PrimaryTermModifier = TermModification.DontModify,
SecondaryTermModifier = TermModification.DontModify;
public string TermPrefix, TermSuffix;
public bool LocalizeOnAwake = true;
private string LastLocalizedLanguage; // Used to avoid Localizing everytime the object is Enabled
#if UNITY_EDITOR
public ILanguageSource
Source; // Source used while in the Editor to preview the Terms (can be of type LanguageSource or LanguageSourceAsset)
#endif
#endregion
#region Variables: Target
public bool IgnoreRTL; // If false, no Right To Left processing will be done
public int
MaxCharactersInRTL; // If the language is RTL, the translation will be split in lines not longer than this amount and the RTL fix will be applied per line
public bool
IgnoreNumbersInRTL =
true; // If the language is RTL, the translation will not convert numbers (will preserve them like: e.g. 123)
public bool
CorrectAlignmentForRTL = true; // If true, when Right To Left language, alignment will be set to Right
public bool
AddSpacesToJoinedLanguages; // Some languages (e.g. Chinese, Japanese and Thai) don't add spaces to their words (all characters are placed toguether), making this variable true, will add spaces to all characters to allow wrapping long texts into multiple lines.
public bool AllowLocalizedParameters = true;
public bool AllowParameters = true;
#endregion
#region Variables: References
public List<Object>
TranslatedObjects = new(); // For targets that reference objects (e.g. AudioSource, UITexture,etc)
// this keeps a reference to the possible options.
// If the value is not the name of any of this objects then it will try to load the object from the Resources
// if either the primary or secondary term is missing, get them. (e.g. from the label's text and font name)
[NonSerialized]
public Dictionary<string, Object>
mAssetDictionary =
new(StringComparer
.Ordinal); //This is used to overcome the issue with Unity not serializing Dictionaries
#endregion
#region Variable Translation Modifiers
public UnityEvent
LocalizeEvent =
new(); // This allows scripts to modify the translations : e.g. "Player {0} wins" -> "Player Red wins"
public static string MainTranslation, SecondaryTranslation; // The callback should use and modify this variables
public static string
CallBackTerm,
CallBackSecondaryTerm; // during the callback, this will hold the FinalTerm and FinalSecondary to know what terms are originating the translation
public static Localize
CurrentLocalizeComponent; // while in the LocalizeCallBack, this points to the Localize calling the callback
public bool
AlwaysForceLocalize; // Force localization when the object gets enabled (useful for callbacks and parameters that change the localization even through the language is the same as in the previous time it was localized)
[SerializeField]
public EventCallback
LocalizeCallBack = new(); //LocalizeCallBack is deprecated. Please use LocalizeEvent instead.
#endregion
#region Variables: Editor Related
public bool mGUI_ShowReferences;
public bool mGUI_ShowTems = true;
public bool mGUI_ShowCallback;
#endregion
#region Variables: Runtime (LocalizeTarget)
public ILocalizeTarget mLocalizeTarget;
public string mLocalizeTargetName; // Used to resolve multiple targets in a prefab
#endregion
#region Localize
private void Awake()
{
#if UNITY_EDITOR
if (BuildPipeline.isBuildingPlayer)
return;
#endif
UpdateAssetDictionary();
FindTarget();
if (LocalizeOnAwake)
OnLocalize();
}
#if UNITY_EDITOR
private void OnValidate()
{
if (LocalizeCallBack.HasCallback())
{
try
{
var methodInfo = UnityEventBase.GetValidMethodInfo(LocalizeCallBack.Target,
LocalizeCallBack.MethodName, Array.Empty<Type>());
if (methodInfo != null)
{
var methodDelegate =
Delegate.CreateDelegate(typeof(UnityAction), LocalizeCallBack.Target, methodInfo,
false) as UnityAction;
if (methodDelegate != null)
UnityEventTools.AddPersistentListener(LocalizeEvent, methodDelegate);
}
}
catch (Exception)
{
}
LocalizeCallBack.Target = null;
LocalizeCallBack.MethodName = null;
}
}
#endif
private void OnEnable()
{
OnLocalize();
}
public bool HasCallback()
{
if (LocalizeCallBack.HasCallback())
return true;
return LocalizeEvent.GetPersistentEventCount() > 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);
var hasCallback = I2Utils.IsPlaying() && HasCallback();
if (!hasCallback && string.IsNullOrEmpty(FinalTerm) && string.IsNullOrEmpty(FinalSecondaryTerm))
return;
CurrentLocalizeComponent = this;
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;
{
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;
var 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 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;
}
#endregion
#region Finding Term
// 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);
@@ -320,199 +381,183 @@ namespace I2.Loc
// If there are values already set, go with those
if (!string.IsNullOrEmpty(mTerm))
primaryTerm = mTerm;
primaryTerm = mTerm;
if (!string.IsNullOrEmpty(mTermSecondary))
secondaryTerm = mTermSecondary;
if (!string.IsNullOrEmpty(mTermSecondary))
secondaryTerm = mTermSecondary;
if (primaryTerm != null)
primaryTerm = primaryTerm.Trim();
if (secondaryTerm != null)
secondaryTerm = secondaryTerm.Trim();
}
if (primaryTerm != null)
primaryTerm = primaryTerm.Trim();
if (secondaryTerm != null)
secondaryTerm = secondaryTerm.Trim();
}
public string GetMainTargetsText()
{
string primary = null, secondary = null;
public string GetMainTargetsText()
{
string primary = null, secondary = null;
if (mLocalizeTarget!=null)
mLocalizeTarget.GetFinalTerms( this, null, null, out primary, out secondary );
if (mLocalizeTarget != null)
mLocalizeTarget.GetFinalTerms(this, null, null, out primary, out secondary);
return string.IsNullOrEmpty(primary) ? mTerm : primary;
}
public void SetFinalTerms( string Main, string Secondary, out string primaryTerm, out string secondaryTerm, bool RemoveNonASCII )
{
primaryTerm = RemoveNonASCII ? I2Utils.GetValidTermName(Main) : Main;
secondaryTerm = Secondary;
}
#endregion
return string.IsNullOrEmpty(primary) ? mTerm : primary;
}
#region Misc
public void SetFinalTerms(string Main, string Secondary, out string primaryTerm, out string secondaryTerm,
bool RemoveNonASCII)
{
primaryTerm = RemoveNonASCII ? I2Utils.GetValidTermName(Main) : Main;
secondaryTerm = Secondary;
}
public void SetTerm (string primary)
{
if (!string.IsNullOrEmpty(primary))
FinalTerm = mTerm = primary;
#endregion
OnLocalize (true);
}
#region Misc
public void SetTerm(string primary, string secondary )
{
if (!string.IsNullOrEmpty(primary))
FinalTerm = mTerm = primary;
FinalSecondaryTerm = mTermSecondary = secondary;
public void SetTerm(string primary)
{
if (!string.IsNullOrEmpty(primary))
FinalTerm = mTerm = primary;
OnLocalize(true);
}
OnLocalize(true);
}
internal T GetSecondaryTranslatedObj<T>( ref string mainTranslation, ref string secondaryTranslation ) where T: Object
{
string newMain, newSecond;
public void SetTerm(string primary, string secondary)
{
if (!string.IsNullOrEmpty(primary))
FinalTerm = mTerm = primary;
FinalSecondaryTerm = mTermSecondary = secondary;
//--[ Allow main translation to override Secondary ]-------------------
DeserializeTranslation(mainTranslation, out newMain, out newSecond);
OnLocalize(true);
}
T obj = null;
internal T GetSecondaryTranslatedObj<T>(ref string mainTranslation, ref string secondaryTranslation)
where T : Object
{
string newMain, newSecond;
if (!string.IsNullOrEmpty(newSecond))
{
obj = GetObject<T>(newSecond);
if (obj != null)
{
mainTranslation = newMain;
secondaryTranslation = newSecond;
}
}
//--[ Allow main translation to override Secondary ]-------------------
DeserializeTranslation(mainTranslation, out newMain, out newSecond);
if (obj == null)
obj = GetObject<T>(secondaryTranslation);
T obj = null;
return obj;
}
if (!string.IsNullOrEmpty(newSecond))
{
obj = GetObject<T>(newSecond);
if (obj != null)
{
mainTranslation = newMain;
secondaryTranslation = newSecond;
}
}
if (obj == null)
obj = GetObject<T>(secondaryTranslation);
return obj;
}
public void UpdateAssetDictionary()
{
TranslatedObjects.RemoveAll(x => x == null);
mAssetDictionary = TranslatedObjects.Distinct()
.GroupBy(o => o.name)
.ToDictionary(g => g.Key, g => g.First());
.GroupBy(o => o.name)
.ToDictionary(g => g.Key, g => g.First());
}
internal T GetObject<T>( string Translation) where T: Object
{
if (string.IsNullOrEmpty (Translation))
return null;
T obj = GetTranslatedObject<T>(Translation);
//if (obj==null)
//{
// Remove path and search by name
//int Index = Translation.LastIndexOfAny("/\\".ToCharArray());
//if (Index>=0)
//{
// Translation = Translation.Substring(Index+1);
// obj = GetTranslatedObject<T>(Translation);
//}
//}
return obj;
}
internal T GetObject<T>(string Translation) where T : Object
{
if (string.IsNullOrEmpty(Translation))
return null;
var obj = GetTranslatedObject<T>(Translation);
T GetTranslatedObject<T>( string Translation) where T: Object
{
T Obj = FindTranslatedObject<T>(Translation);
/*if (Obj == null)
return null;
if ((Obj as T) != null)
return Obj as T;
// If the found Obj is not of type T, then try finding a component inside
if (Obj as Component != null)
return (Obj as Component).GetComponent(typeof(T)) as T;
if (Obj as GameObject != null)
return (Obj as GameObject).GetComponent(typeof(T)) as T;
*/
return Obj;
}
//if (obj==null)
//{
// Remove path and search by name
//int Index = Translation.LastIndexOfAny("/\\".ToCharArray());
//if (Index>=0)
//{
// Translation = Translation.Substring(Index+1);
// obj = GetTranslatedObject<T>(Translation);
//}
//}
return obj;
}
private T GetTranslatedObject<T>(string Translation) where T : Object
{
var Obj = FindTranslatedObject<T>(Translation);
/*if (Obj == null)
return null;
if ((Obj as T) != null)
return Obj as T;
// If the found Obj is not of type T, then try finding a component inside
if (Obj as Component != null)
return (Obj as Component).GetComponent(typeof(T)) as T;
if (Obj as GameObject != null)
return (Obj as GameObject).GetComponent(typeof(T)) as T;
*/
return Obj;
}
// translation format: "[secondary]value" [secondary] is optional
void DeserializeTranslation( string translation, out string value, out string secondary )
{
if (!string.IsNullOrEmpty(translation) && translation.Length>1 && translation[0]=='[')
{
int Index = translation.IndexOf(']');
if (Index>0)
{
secondary = translation.Substring(1, Index-1);
value = translation.Substring(Index+1);
return;
}
}
value = translation;
secondary = string.Empty;
}
public T FindTranslatedObject<T>( string value) where T : Object
{
if (string.IsNullOrEmpty(value))
return null;
if (mAssetDictionary == null || mAssetDictionary.Count != TranslatedObjects.Count)
// translation format: "[secondary]value" [secondary] is optional
private void DeserializeTranslation(string translation, out string value, out string secondary)
{
if (!string.IsNullOrEmpty(translation) && translation.Length > 1 && translation[0] == '[')
{
UpdateAssetDictionary();
var Index = translation.IndexOf(']');
if (Index > 0)
{
secondary = translation.Substring(1, Index - 1);
value = translation.Substring(Index + 1);
return;
}
}
value = translation;
secondary = string.Empty;
}
public T FindTranslatedObject<T>(string value) where T : Object
{
if (string.IsNullOrEmpty(value))
return null;
if (mAssetDictionary == null || mAssetDictionary.Count != TranslatedObjects.Count) UpdateAssetDictionary();
foreach (var kvp in mAssetDictionary)
{
if (kvp.Value is T && value.EndsWith(kvp.Key, StringComparison.OrdinalIgnoreCase))
{
// Check if the value is just the name or has a path
if (string.Compare(value, kvp.Key, StringComparison.OrdinalIgnoreCase)==0)
return (T) kvp.Value;
if (kvp.Value is T && value.EndsWith(kvp.Key, StringComparison.OrdinalIgnoreCase))
// Check if the value is just the name or has a path
if (string.Compare(value, kvp.Key, StringComparison.OrdinalIgnoreCase) == 0)
return (T)kvp.Value;
// Check if the path matches
//Resources.get TranslatedObjects[i].
var obj = LocalizationManager.FindAsset(value) as T;
if (obj)
return obj;
// Check if the path matches
//Resources.get TranslatedObjects[i].
}
}
obj = ResourceManager.pInstance.GetAsset<T>(value);
return obj;
}
T obj = LocalizationManager.FindAsset(value) as T;
if (obj)
return obj;
public bool HasTranslatedObject(Object Obj)
{
if (TranslatedObjects.Contains(Obj))
return true;
return ResourceManager.pInstance.HasAsset(Obj);
}
obj = ResourceManager.pInstance.GetAsset<T>(value);
return obj;
}
public bool HasTranslatedObject( Object Obj )
{
if (TranslatedObjects.Contains(Obj))
return true;
return ResourceManager.pInstance.HasAsset(Obj);
}
public void AddTranslatedObject( Object Obj )
{
public void AddTranslatedObject(Object Obj)
{
if (TranslatedObjects.Contains(Obj))
return;
TranslatedObjects.Add(Obj);
TranslatedObjects.Add(Obj);
UpdateAssetDictionary();
}
}
#endregion
#region Utilities
// This can be used to set the language when a button is clicked
public void SetGlobalLanguage( string Language )
{
LocalizationManager.CurrentLanguage = Language;
}
#endregion
}
#endregion
}
}