public static T TryResolveDef <T>(string defName, FailMode failReportMode, object debugWanterInfo = null)
 {
     DeepProfiler.Start("TryResolveDef");
     try
     {
         T val = (T)(object)GenDefDatabase.GetDefSilentFail(typeof(T), defName);
         if (val != null)
         {
             return(val);
         }
         if (failReportMode == FailMode.LogErrors)
         {
             string text = string.Concat("Could not resolve cross-reference to ", typeof(T), " named ", defName);
             if (debugWanterInfo != null)
             {
                 text = text + " (wanter=" + debugWanterInfo.ToStringSafe() + ")";
             }
             Log.Error(text);
         }
         return(default(T));
     }
     finally
     {
         DeepProfiler.End();
     }
 }
            public override bool TryResolve(FailMode failReportMode)
            {
                if (this.fi == null)
                {
                    Log.Error("Trying to resolve null field for def named " + this.defName.ToStringSafe());
                    return(false);
                }
                Def defSilentFail = GenDefDatabase.GetDefSilentFail(this.fi.FieldType, this.defName);

                if (defSilentFail == null)
                {
                    if (failReportMode == FailMode.LogErrors)
                    {
                        Log.Error("Could not resolve cross-reference: No " + this.fi.FieldType + " named " + this.defName.ToStringSafe() + " found to give to " + base.wanter.GetType() + " " + base.wanter.ToStringSafe());
                    }
                    return(false);
                }
                SoundDef soundDef = defSilentFail as SoundDef;

                if (soundDef != null && soundDef.isUndefined)
                {
                    Log.Warning("Could not resolve cross-reference: No " + this.fi.FieldType + " named " + this.defName.ToStringSafe() + " found to give to " + base.wanter.GetType() + " " + base.wanter.ToStringSafe() + " (using undefined sound instead)");
                }
                this.fi.SetValue(base.wanter, defSilentFail);
                return(true);
            }
            public override bool TryResolve(FailMode failReportMode)
            {
                if (fi == null)
                {
                    Log.Error("Trying to resolve null field for def named " + defName.ToStringSafe());
                    return(false);
                }
                Type type = overrideFieldType ?? fi.FieldType;

                resolvedDef = GenDefDatabase.GetDefSilentFail(type, defName);
                if (resolvedDef == null)
                {
                    if (failReportMode == FailMode.LogErrors && !BadCrossRefAllowed)
                    {
                        Log.Error(string.Concat("Could not resolve cross-reference: No ", type, " named ", defName.ToStringSafe(), " found to give to ", wanter.GetType(), " ", wanter.ToStringSafe()));
                    }
                    return(false);
                }
                SoundDef soundDef = resolvedDef as SoundDef;

                if (soundDef != null && soundDef.isUndefined)
                {
                    Log.Warning(string.Concat("Could not resolve cross-reference: No ", type, " named ", defName.ToStringSafe(), " found to give to ", wanter.GetType(), " ", wanter.ToStringSafe(), " (using undefined sound instead)"));
                }
                fi.SetValue(wanter, resolvedDef);
                return(true);
            }
예제 #4
0
        public static string BackCompatibleDefName(Type defType, string defName, bool forDefInjections = false, XmlNode node = null)
        {
            if (GenDefDatabase.GetDefSilentFail(defType, defName, specialCaseForSoundDefs: false) != null)
            {
                return(defName);
            }
            string text = defName;

            for (int i = 0; i < conversionChain.Count; i++)
            {
                if (Scribe.mode != 0 && !conversionChain[i].AppliesToLoadedGameVersion())
                {
                    continue;
                }
                try
                {
                    string text2 = conversionChain[i].BackCompatibleDefName(defType, text, forDefInjections, node);
                    if (text2 != null)
                    {
                        text = text2;
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(string.Concat("Error in BackCompatibleDefName of ", conversionChain[i].GetType(), "\n", ex));
                }
            }
            return(text);
        }
예제 #5
0
        public static void GiveAllShortHashes()
        {
            ShortHashGiver.takenHashesPerDeftype.Clear();
            List <Def> list = new List <Def>();

            foreach (Type current in GenDefDatabase.AllDefTypesWithDatabases())
            {
                Type type = typeof(DefDatabase <>).MakeGenericType(new Type[]
                {
                    current
                });
                PropertyInfo property   = type.GetProperty("AllDefs");
                MethodInfo   getMethod  = property.GetGetMethod();
                IEnumerable  enumerable = (IEnumerable)getMethod.Invoke(null, null);
                list.Clear();
                foreach (Def item in enumerable)
                {
                    list.Add(item);
                }
                list.SortBy((Def d) => d.defName);
                for (int i = 0; i < list.Count; i++)
                {
                    ShortHashGiver.GiveShortHash(list[i], current);
                }
            }
        }
예제 #6
0
        public static void DefLabels()
        {
            List <DebugMenuOption> list = new List <DebugMenuOption>();

            foreach (Type type in from def in GenDefDatabase.AllDefTypesWithDatabases()
                     orderby def.Name
                     select def)
            {
                DebugMenuOption item = new DebugMenuOption(type.Name, DebugMenuOptionMode.Action, delegate
                {
                    IEnumerable source          = (IEnumerable)GenGeneric.GetStaticPropertyOnGenericType(typeof(DefDatabase <>), type, "AllDefs");
                    int num                     = 0;
                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (Def item2 in source.Cast <Def>())
                    {
                        stringBuilder.AppendLine(item2.label);
                        num++;
                        if (num >= 500)
                        {
                            Log.Message(stringBuilder.ToString());
                            stringBuilder = new StringBuilder();
                            num           = 0;
                        }
                    }
                    Log.Message(stringBuilder.ToString());
                });
                list.Add(item);
            }
            Find.WindowStack.Add(new Dialog_DebugOptionListLister(list));
        }
        public static T TryResolveDef <T>(string defName, FailMode failReportMode, object debugWanterInfo = null)
        {
            T t = (T)((object)GenDefDatabase.GetDefSilentFail(typeof(T), defName, true));

            if (t != null)
            {
                return(t);
            }
            if (failReportMode == FailMode.LogErrors)
            {
                string text = string.Concat(new object[]
                {
                    "Could not resolve cross-reference to ",
                    typeof(T),
                    " named ",
                    defName
                });
                if (debugWanterInfo != null)
                {
                    text = text + " (wanter=" + debugWanterInfo.ToStringSafe <object>() + ")";
                }
                Log.Error(text, false);
            }
            return(default(T));
        }
예제 #8
0
        public static void DefNamesAll()
        {
            StringBuilder stringBuilder = new StringBuilder();
            int           num           = 0;

            foreach (Type item in from def in GenDefDatabase.AllDefTypesWithDatabases()
                     orderby def.Name
                     select def)
            {
                IEnumerable source = (IEnumerable)GenGeneric.GetStaticPropertyOnGenericType(typeof(DefDatabase <>), item, "AllDefs");
                stringBuilder.AppendLine("--    " + item.ToString());
                foreach (Def item2 in from Def def in source
                         orderby def.defName
                         select def)
                {
                    stringBuilder.AppendLine(item2.defName);
                    num++;
                    if (num >= 500)
                    {
                        Log.Message(stringBuilder.ToString());
                        stringBuilder = new StringBuilder();
                        num           = 0;
                    }
                }
                stringBuilder.AppendLine();
                stringBuilder.AppendLine();
            }
            Log.Message(stringBuilder.ToString());
        }
예제 #9
0
        public static void AddAllInMods()
        {
            HashSet <string> hashSet = new HashSet <string>();

            foreach (ModContentPack item in (from m in LoadedModManager.RunningMods
                                             orderby m.OverwritePriority
                                             select m).ThenBy((ModContentPack x) => LoadedModManager.RunningModsListForReading.IndexOf(x)))
            {
                hashSet.Clear();
                foreach (T item2 in GenDefDatabase.DefsToGoInDatabase <T>(item))
                {
                    if (hashSet.Contains(item2.defName))
                    {
                        Log.Error("Mod " + item + " has multiple " + typeof(T) + "s named " + item2.defName + ". Skipping.");
                    }
                    else
                    {
                        if (item2.defName == "UnnamedDef")
                        {
                            string text = "Unnamed" + typeof(T).Name + Rand.Range(1, 100000).ToString() + "A";
                            Log.Error(typeof(T).Name + " in " + item.ToString() + " with label " + item2.label + " lacks a defName. Giving name " + text);
                            item2.defName = text;
                        }
                        if (defsByName.TryGetValue(item2.defName, out T value))
                        {
                            Remove(value);
                        }
                        Add(item2);
                    }
                }
            }
        }
예제 #10
0
        public static void AddAllInMods()
        {
            HashSet <string> hashSet = new HashSet <string>();

            foreach (ModContentPack item in Enumerable.ThenBy <ModContentPack, int>(Enumerable.OrderBy <ModContentPack, int>(LoadedModManager.RunningMods, (Func <ModContentPack, int>)((ModContentPack m) => m.OverwritePriority)), (Func <ModContentPack, int>)((ModContentPack x) => LoadedModManager.RunningModsListForReading.IndexOf(x))))
            {
                hashSet.Clear();
                foreach (T item2 in GenDefDatabase.DefsToGoInDatabase <T>(item))
                {
                    if (hashSet.Contains(((Def)(object)item2).defName))
                    {
                        Log.Error("Mod " + item + " has multiple " + typeof(T) + "s named " + ((Def)(object)item2).defName + ". Skipping.");
                    }
                    else
                    {
                        if (((Def)(object)item2).defName == "UnnamedDef")
                        {
                            string text = "Unnamed" + typeof(T).Name + Rand.Range(1, 100000).ToString() + "A";
                            Log.Error(typeof(T).Name + " in " + item.ToString() + " with label " + ((Def)(object)item2).label + " lacks a defName. Giving name " + text);
                            ((Def)(object)item2).defName = text;
                        }
                        T def = default(T);
                        if (DefDatabase <T> .defsByName.TryGetValue(((Def)(object)item2).defName, out def))
                        {
                            DefDatabase <T> .Remove(def);
                        }
                        DefDatabase <T> .Add(item2);
                    }
                }
            }
        }
예제 #11
0
        public static void ForEachPossibleDefInjection(Type defType, DefInjectionUtility.PossibleDefInjectionTraverser action)
        {
            IEnumerable <Def> allDefsInDatabaseForDef = GenDefDatabase.GetAllDefsInDatabaseForDef(defType);

            foreach (Def def in allDefsInDatabaseForDef)
            {
                DefInjectionUtility.ForEachPossibleDefInjectionInDef(def, action);
            }
        }
예제 #12
0
 private void EnsureAllDefTypesHaveDefInjectionPackage()
 {
     foreach (Type defType in GenDefDatabase.AllDefTypesWithDatabases())
     {
         if (!this.defInjections.Any((DefInjectionPackage x) => x.defType == defType))
         {
             this.defInjections.Add(new DefInjectionPackage(defType));
         }
     }
 }
예제 #13
0
 private void EnsureAllDefTypesHaveDefInjectionPackage()
 {
     foreach (Type item in GenDefDatabase.AllDefTypesWithDatabases())
     {
         if (!defInjections.Any((DefInjectionPackage x) => x.defType == item))
         {
             defInjections.Add(new DefInjectionPackage(item));
         }
     }
 }
 public static void ForEachPossibleDefInjection(Type defType, PossibleDefInjectionTraverser action, ModMetaData onlyFromMod = null)
 {
     foreach (Def item in GenDefDatabase.GetAllDefsInDatabaseForDef(defType))
     {
         if (onlyFromMod == null || (item.modContentPack != null && !(item.modContentPack.PackageId != onlyFromMod.PackageId)))
         {
             ForEachPossibleDefInjectionInDef(item, action);
         }
     }
 }
            public override bool TryResolve(FailMode failReportMode)
            {
                bool result;

                if (this.fi == null)
                {
                    Log.Error("Trying to resolve null field for def named " + this.defName.ToStringSafe <string>(), false);
                    result = false;
                }
                else
                {
                    Def defSilentFail = GenDefDatabase.GetDefSilentFail(this.fi.FieldType, this.defName, true);
                    if (defSilentFail == null)
                    {
                        if (failReportMode == FailMode.LogErrors)
                        {
                            Log.Error(string.Concat(new object[]
                            {
                                "Could not resolve cross-reference: No ",
                                this.fi.FieldType,
                                " named ",
                                this.defName.ToStringSafe <string>(),
                                " found to give to ",
                                this.wanter.GetType(),
                                " ",
                                this.wanter.ToStringSafe <object>()
                            }), false);
                        }
                        result = false;
                    }
                    else
                    {
                        SoundDef soundDef = defSilentFail as SoundDef;
                        if (soundDef != null && soundDef.isUndefined)
                        {
                            Log.Warning(string.Concat(new object[]
                            {
                                "Could not resolve cross-reference: No ",
                                this.fi.FieldType,
                                " named ",
                                this.defName.ToStringSafe <string>(),
                                " found to give to ",
                                this.wanter.GetType(),
                                " ",
                                this.wanter.ToStringSafe <object>(),
                                " (using undefined sound instead)"
                            }), false);
                        }
                        this.fi.SetValue(this.wanter, defSilentFail);
                        result = true;
                    }
                }
                return(result);
            }
예제 #16
0
        private static void CleanupDefInjections()
        {
            string        activeLanguageCoreModFolderPath = GetActiveLanguageCoreModFolderPath();
            string        text          = Path.Combine(activeLanguageCoreModFolderPath, "DefLinked");
            string        text2         = Path.Combine(activeLanguageCoreModFolderPath, "DefInjected");
            DirectoryInfo directoryInfo = new DirectoryInfo(text);

            if (directoryInfo.Exists)
            {
                if (!Directory.Exists(text2))
                {
                    Directory.Move(text, text2);
                    Thread.Sleep(1000);
                    directoryInfo = new DirectoryInfo(text2);
                }
            }
            else
            {
                directoryInfo = new DirectoryInfo(text2);
            }
            if (!directoryInfo.Exists)
            {
                Log.Error("Could not find def-injections folder for the active language.");
            }
            else
            {
                FileInfo[] files = directoryInfo.GetFiles("*.xml", SearchOption.AllDirectories);
                foreach (FileInfo fileInfo in files)
                {
                    try
                    {
                        fileInfo.Delete();
                    }
                    catch (Exception ex)
                    {
                        Log.Error("Could not delete " + fileInfo.Name + ": " + ex);
                    }
                }
                foreach (Type item in GenDefDatabase.AllDefTypesWithDatabases())
                {
                    try
                    {
                        CleanupDefInjectionsForDefType(item, directoryInfo.FullName);
                    }
                    catch (Exception ex2)
                    {
                        Log.Error("Could not process def-injections for type " + item.Name + ": " + ex2);
                    }
                }
            }
        }
        public static void AddAllInMods()
        {
            HashSet <string> hashSet = new HashSet <string>();

            foreach (ModContentPack modContentPack in (from m in LoadedModManager.RunningMods
                                                       orderby m.OverwritePriority
                                                       select m).ThenBy((ModContentPack x) => LoadedModManager.RunningModsListForReading.IndexOf(x)))
            {
                hashSet.Clear();
                foreach (T t in GenDefDatabase.DefsToGoInDatabase <T>(modContentPack))
                {
                    if (hashSet.Contains(t.defName))
                    {
                        Log.Error(string.Concat(new object[]
                        {
                            "Mod ",
                            modContentPack,
                            " has multiple ",
                            typeof(T),
                            "s named ",
                            t.defName,
                            ". Skipping."
                        }), false);
                    }
                    else
                    {
                        if (t.defName == "UnnamedDef")
                        {
                            string text = "Unnamed" + typeof(T).Name + Rand.Range(1, 100000).ToString() + "A";
                            Log.Error(string.Concat(new string[]
                            {
                                typeof(T).Name,
                                " in ",
                                modContentPack.ToString(),
                                " with label ",
                                t.label,
                                " lacks a defName. Giving name ",
                                text
                            }), false);
                            t.defName = text;
                        }
                        T def;
                        if (DefDatabase <T> .defsByName.TryGetValue(t.defName, out def))
                        {
                            DefDatabase <T> .Remove(def);
                        }
                        DefDatabase <T> .Add(t);
                    }
                }
            }
        }
 private static void CleanupDefInjections()
 {
     foreach (ModMetaData item in ModsConfig.ActiveModsInLoadOrder)
     {
         string        languageFolderPath = GetLanguageFolderPath(LanguageDatabase.activeLanguage, item.RootDir.FullName);
         string        text          = Path.Combine(languageFolderPath, "DefLinked");
         string        text2         = Path.Combine(languageFolderPath, "DefInjected");
         DirectoryInfo directoryInfo = new DirectoryInfo(text);
         if (directoryInfo.Exists)
         {
             if (!Directory.Exists(text2))
             {
                 Directory.Move(text, text2);
                 Thread.Sleep(1000);
                 directoryInfo = new DirectoryInfo(text2);
             }
         }
         else
         {
             directoryInfo = new DirectoryInfo(text2);
         }
         if (!directoryInfo.Exists)
         {
             directoryInfo.Create();
         }
         FileInfo[] files = directoryInfo.GetFiles("*.xml", SearchOption.AllDirectories);
         foreach (FileInfo fileInfo in files)
         {
             try
             {
                 fileInfo.Delete();
             }
             catch (Exception ex)
             {
                 Log.Error("Could not delete " + fileInfo.Name + ": " + ex);
             }
         }
         foreach (Type item2 in GenDefDatabase.AllDefTypesWithDatabases())
         {
             try
             {
                 CleanupDefInjectionsForDefType(item2, directoryInfo.FullName, item);
             }
             catch (Exception ex2)
             {
                 Log.Error("Could not process def-injections for type " + item2.Name + ": " + ex2);
             }
         }
     }
 }
        public static T TryResolveDef <T>(string defName, FailMode failReportMode)
        {
            T val = (T)(object)GenDefDatabase.GetDefSilentFail(typeof(T), defName);

            if (val != null)
            {
                return(val);
            }
            if (failReportMode == FailMode.LogErrors)
            {
                Log.Error("Could not resolve cross-reference to " + typeof(T) + " named " + defName);
            }
            return(default(T));
        }
예제 #20
0
 private void EnsureAllDefTypesHaveDefInjectionPackage()
 {
     using (IEnumerator <Type> enumerator = GenDefDatabase.AllDefTypesWithDatabases().GetEnumerator())
     {
         while (enumerator.MoveNext())
         {
             Type defType = enumerator.Current;
             if (!this.defInjections.Any((DefInjectionPackage x) => x.defType == defType))
             {
                 this.defInjections.Add(new DefInjectionPackage(defType));
             }
         }
     }
 }
예제 #21
0
            public bool ModifiesDefFromModOrNullCore(ModMetaData mod, Type defType)
            {
                Def defSilentFail = GenDefDatabase.GetDefSilentFail(defType, DefName);

                if (defSilentFail == null)
                {
                    return(mod.IsCoreMod);
                }
                if (mod == null)
                {
                    return(defSilentFail.modContentPack == null);
                }
                if (defSilentFail.modContentPack != null)
                {
                    return(defSilentFail.modContentPack.FolderName == mod.FolderName);
                }
                return(false);
            }
예제 #22
0
        public static T TryResolveDef <T>(string defName, FailMode failReportMode, object debugWanterInfo = null)
        {
            T val = (T)(object)GenDefDatabase.GetDefSilentFail(typeof(T), defName);

            if (val != null)
            {
                return(val);
            }
            if (failReportMode == FailMode.LogErrors)
            {
                string text = "Could not resolve cross-reference to " + typeof(T) + " named " + defName;
                if (debugWanterInfo != null)
                {
                    text = text + " (wanter=" + debugWanterInfo.ToStringSafe() + ")";
                }
                Log.Error(text);
            }
            return(default(T));
        }
        public static T TryResolveDef <T>(string defName, FailMode failReportMode)
        {
            T t = (T)((object)GenDefDatabase.GetDefSilentFail(typeof(T), defName));

            if (t != null)
            {
                return(t);
            }
            if (failReportMode == FailMode.LogErrors)
            {
                Log.Error(string.Concat(new object[]
                {
                    "Could not resolve cross-reference to ",
                    typeof(T),
                    " named ",
                    defName
                }));
            }
            return(default(T));
        }
예제 #24
0
        public static void GiveAllShortHashes()
        {
            takenHashesPerDeftype.Clear();
            List <Def> list = new List <Def>();

            foreach (Type item2 in GenDefDatabase.AllDefTypesWithDatabases())
            {
                IEnumerable obj = (IEnumerable)typeof(DefDatabase <>).MakeGenericType(item2).GetProperty("AllDefs").GetGetMethod()
                                  .Invoke(null, null);
                list.Clear();
                foreach (Def item3 in obj)
                {
                    list.Add(item3);
                }
                list.SortBy((Def d) => d.defName);
                for (int i = 0; i < list.Count; i++)
                {
                    GiveShortHash(list[i], item2);
                }
            }
        }
예제 #25
0
        public static void GiveAllShortHashes()
        {
            ShortHashGiver.takenHashesPerDeftype.Clear();
            List <Def> list = new List <Def>();

            foreach (Type type in GenDefDatabase.AllDefTypesWithDatabases())
            {
                Type type2 = typeof(DefDatabase <>).MakeGenericType(new Type[]
                {
                    type
                });
                PropertyInfo property   = type2.GetProperty("AllDefs");
                MethodInfo   getMethod  = property.GetGetMethod();
                IEnumerable  enumerable = (IEnumerable)getMethod.Invoke(null, null);
                list.Clear();
                IEnumerator enumerator2 = enumerable.GetEnumerator();
                try
                {
                    while (enumerator2.MoveNext())
                    {
                        object obj  = enumerator2.Current;
                        Def    item = (Def)obj;
                        list.Add(item);
                    }
                }
                finally
                {
                    IDisposable disposable;
                    if ((disposable = (enumerator2 as IDisposable)) != null)
                    {
                        disposable.Dispose();
                    }
                }
                list.SortBy((Def d) => d.defName);
                for (int i = 0; i < list.Count; i++)
                {
                    ShortHashGiver.GiveShortHash(list[i], type);
                }
            }
        }
예제 #26
0
        public static void AddAllInMods()
        {
            HashSet <string> hashSet = new HashSet <string>();

            foreach (ModContentPack item in LoadedModManager.RunningMods.OrderBy((ModContentPack m) => m.OverwritePriority).ThenBy((ModContentPack x) => LoadedModManager.RunningModsListForReading.IndexOf(x)))
            {
                hashSet.Clear();
                foreach (T item2 in GenDefDatabase.DefsToGoInDatabase <T>(item))
                {
                    if (!hashSet.Add(item2.defName))
                    {
                        Log.Error("Mod " + item + " has multiple " + typeof(T) + "s named " + item2.defName + ". Skipping.");
                    }
                    else
                    {
                        AddDef(item2, item.ToString());
                    }
                }
            }
            foreach (T item3 in LoadedModManager.PatchedDefsForReading.OfType <T>())
            {
                AddDef(item3, "Patches");
            }
            void AddDef(T def, string sourceName)
            {
                if (def.defName == "UnnamedDef")
                {
                    string text = "Unnamed" + typeof(T).Name + Rand.Range(1, 100000).ToString() + "A";
                    Log.Error(typeof(T).Name + " in " + sourceName + " with label " + def.label + " lacks a defName. Giving name " + text);
                    def.defName = text;
                }
                if (defsByName.TryGetValue(def.defName, out T value))
                {
                    Remove(value);
                }
                Add(def);
            }
        }
예제 #27
0
        public static void AddAllInMods()
        {
            HashSet <string> hashSet = new HashSet <string>();

            foreach (ModContentPack item in LoadedModManager.RunningMods.OrderBy((ModContentPack m) => m.OverwritePriority).ThenBy((ModContentPack x) => LoadedModManager.RunningModsListForReading.IndexOf(x)))
            {
                hashSet.Clear();
                foreach (T item2 in GenDefDatabase.DefsToGoInDatabase <T>(item))
                {
                    if (!hashSet.Add(item2.defName))
                    {
                        Log.Error(string.Concat("Mod ", item, " has multiple ", typeof(T), "s named ", item2.defName, ". Skipping."));
                    }
                    else
                    {
                        AddDef(item2, item.ToString());
                    }
                }
            }
            foreach (T item3 in LoadedModManager.PatchedDefsForReading.OfType <T>())
            {
                AddDef(item3, "Patches");
            }
예제 #28
0
        public static object Convert(object obj, Type to, object defaultValue)
        {
            if (obj == null)
            {
                return(defaultValue);
            }
            if (to.IsAssignableFrom(obj.GetType()))
            {
                return(obj);
            }
            if (to == typeof(string))
            {
                return(obj.ToString());
            }
            string text = obj as string;

            if (text != null && !to.IsPrimitive && ParseHelper.CanParse(to, (string)obj))
            {
                if (text == "")
                {
                    return(defaultValue);
                }
                return(ParseHelper.FromString(text, to));
            }
            if (text != null && typeof(Def).IsAssignableFrom(to))
            {
                if (text == "")
                {
                    return(defaultValue);
                }
                return(GenDefDatabase.GetDef(to, text));
            }
            if (text != null && to == typeof(Faction))
            {
                if (text == "")
                {
                    return(defaultValue);
                }
                List <Faction> allFactionsListForReading = Find.FactionManager.AllFactionsListForReading;
                for (int i = 0; i < allFactionsListForReading.Count; i++)
                {
                    if (allFactionsListForReading[i].GetUniqueLoadID() == text)
                    {
                        return(allFactionsListForReading[i]);
                    }
                }
                for (int j = 0; j < allFactionsListForReading.Count; j++)
                {
                    if (allFactionsListForReading[j].HasName && allFactionsListForReading[j].Name == text)
                    {
                        return(allFactionsListForReading[j]);
                    }
                }
                for (int k = 0; k < allFactionsListForReading.Count; k++)
                {
                    if (allFactionsListForReading[k].def.defName == text)
                    {
                        return(allFactionsListForReading[k]);
                    }
                }
                return(defaultValue);
            }
            if (CanConvertBetweenDataTypes(obj.GetType(), to))
            {
                return(ConvertBetweenDataTypes(obj, to));
            }
            if (IsXml(obj) && !to.IsPrimitive)
            {
                try
                {
                    Type type = to;
                    if (type == typeof(IEnumerable))
                    {
                        type = typeof(List <string>);
                    }
                    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable <>) && type.GetGenericArguments().Length >= 1)
                    {
                        type = typeof(List <>).MakeGenericType(type.GetGenericArguments()[0]);
                    }
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n" + text + "\n</root>");
                    object result = DirectXmlToObject.GetObjectFromXmlMethod(type)(xmlDocument.DocumentElement, arg2 : true);
                    DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.LogErrors);
                    return(result);
                }
                finally
                {
                    DirectXmlCrossRefLoader.Clear();
                }
            }
            if (to.IsGenericType && (to.GetGenericTypeDefinition() == typeof(IEnumerable <>) || to.GetGenericTypeDefinition() == typeof(List <>)) && to.GetGenericArguments().Length >= 1 && (!(to.GetGenericArguments()[0] == typeof(string)) || !(obj is string)))
            {
                IEnumerable enumerable = obj as IEnumerable;
                if (enumerable != null)
                {
                    Type type2 = to.GetGenericArguments()[0];
                    bool flag  = true;
                    foreach (object item in enumerable)
                    {
                        if (!CanConvert(item, type2))
                        {
                            flag = false;
                            break;
                        }
                    }
                    if (flag)
                    {
                        IList list = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(type2));
                        {
                            foreach (object item2 in enumerable)
                            {
                                list.Add(Convert(item2, type2));
                            }
                            return(list);
                        }
                    }
                }
            }
            if (obj is IEnumerable && !(obj is string))
            {
                IEnumerable e = (IEnumerable)obj;
                if (GenCollection.Count_EnumerableBase(e) == 1)
                {
                    object obj2 = GenCollection.FirstOrDefault_EnumerableBase(e);
                    if (CanConvert(obj2, to))
                    {
                        return(Convert(obj2, to));
                    }
                }
            }
            if (typeof(IList).IsAssignableFrom(to))
            {
                IList  list2            = (IList)Activator.CreateInstance(to);
                Type[] genericArguments = to.GetGenericArguments();
                if (genericArguments.Length >= 1)
                {
                    list2.Add(Convert(obj, genericArguments[0]));
                }
                else
                {
                    list2.Add(obj);
                }
                return(list2);
            }
            if (to == typeof(IEnumerable))
            {
                return(Gen.YieldSingleNonGeneric(obj));
            }
            if (to.IsGenericType && to.GetGenericTypeDefinition() == typeof(IEnumerable <>))
            {
                Type[] genericArguments2 = to.GetGenericArguments();
                if (genericArguments2.Length >= 1)
                {
                    IList obj3 = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(genericArguments2[0]));
                    obj3.Add(Convert(obj, genericArguments2[0]));
                    return(obj3);
                }
                return(Gen.YieldSingleNonGeneric(obj));
            }
            IConvertible convertible = obj as IConvertible;

            if (convertible == null)
            {
                return(defaultValue);
            }
            try
            {
                return(ConvertToPrimitive(convertible, to, defaultValue));
            }
            catch (FormatException)
            {
                return(defaultValue);
            }
        }
예제 #29
0
        private bool SetDefFieldAtPath(Type defType, string path, object value, Type ensureFieldType, bool errorOnDefNotFound, string fileSource, bool isPlaceholder, out string normalizedPath, out string suggestedPath, out string replacedString, out IEnumerable <string> replacedStringsList)
        {
            replacedString      = null;
            replacedStringsList = null;
            normalizedPath      = path;
            suggestedPath       = path;
            string text = path.Split(new char[]
            {
                '.'
            })[0];

            text = BackCompatibility.BackCompatibleDefName(defType, text, true);
            if (GenDefDatabase.GetDefSilentFail(defType, text, false) == null)
            {
                if (errorOnDefNotFound)
                {
                    this.loadErrors.Add(string.Concat(new object[]
                    {
                        "Found no ",
                        defType,
                        " named ",
                        text,
                        " to match ",
                        path,
                        " (",
                        fileSource,
                        ")"
                    }));
                }
                return(false);
            }
            bool flag = false;
            int  num  = 0;
            bool result;

            try
            {
                List <string> list = path.Split(new char[]
                {
                    '.'
                }).ToList <string>();
                object obj = GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), defType, "GetNamedSilentFail", new object[]
                {
                    list[0]
                });
                if (obj == null)
                {
                    throw new InvalidOperationException("Def named " + list[0] + " not found.");
                }
                list.RemoveAt(0);
                num++;
                string text2;
                int    num2;
                DefInjectionPathPartKind defInjectionPathPartKind;
                FieldInfo field;
                int       num3;
                int       num4;
                while (true)
                {
                    text2 = list[0];
                    num2  = -1;
                    if (int.TryParse(text2, out num2))
                    {
                        defInjectionPathPartKind = DefInjectionPathPartKind.ListIndex;
                    }
                    else if (this.GetFieldNamed(obj.GetType(), text2) != null)
                    {
                        defInjectionPathPartKind = DefInjectionPathPartKind.Field;
                    }
                    else if (obj.GetType().GetProperty("Count") != null)
                    {
                        if (text2.Contains('-'))
                        {
                            defInjectionPathPartKind = DefInjectionPathPartKind.ListHandleWithIndex;
                            string[] array = text2.Split(new char[]
                            {
                                '-'
                            });
                            text2 = array[0];
                            num2  = (int)ParseHelper.FromString(array[1], typeof(int));
                        }
                        else
                        {
                            defInjectionPathPartKind = DefInjectionPathPartKind.ListHandle;
                        }
                    }
                    else
                    {
                        defInjectionPathPartKind = DefInjectionPathPartKind.Field;
                    }
                    if (list.Count == 1)
                    {
                        break;
                    }
                    if (defInjectionPathPartKind == DefInjectionPathPartKind.Field)
                    {
                        field = obj.GetType().GetField(text2, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                        if (field == null)
                        {
                            goto Block_41;
                        }
                        if (field.HasAttribute <NoTranslateAttribute>())
                        {
                            goto Block_42;
                        }
                        if (field.HasAttribute <UnsavedAttribute>())
                        {
                            goto Block_43;
                        }
                        if (field.HasAttribute <TranslationCanChangeCountAttribute>())
                        {
                            flag = true;
                        }
                        if (defInjectionPathPartKind == DefInjectionPathPartKind.Field)
                        {
                            obj = field.GetValue(obj);
                        }
                        else
                        {
                            object       value2   = field.GetValue(obj);
                            PropertyInfo property = value2.GetType().GetProperty("Item");
                            if (property == null)
                            {
                                goto Block_46;
                            }
                            num3 = (int)value2.GetType().GetProperty("Count").GetValue(value2, null);
                            if (num2 < 0 || num2 >= num3)
                            {
                                goto IL_ADC;
                            }
                            obj = property.GetValue(value2, new object[]
                            {
                                num2
                            });
                        }
                    }
                    else if (defInjectionPathPartKind == DefInjectionPathPartKind.ListIndex || defInjectionPathPartKind == DefInjectionPathPartKind.ListHandle || defInjectionPathPartKind == DefInjectionPathPartKind.ListHandleWithIndex)
                    {
                        object       obj2      = obj;
                        PropertyInfo property2 = obj2.GetType().GetProperty("Item");
                        if (property2 == null)
                        {
                            goto Block_50;
                        }
                        bool flag2;
                        if (defInjectionPathPartKind == DefInjectionPathPartKind.ListHandle || defInjectionPathPartKind == DefInjectionPathPartKind.ListHandleWithIndex)
                        {
                            num2 = TranslationHandleUtility.GetElementIndexByHandle(obj2, text2, num2);
                            defInjectionPathPartKind = DefInjectionPathPartKind.ListIndex;
                            flag2 = true;
                        }
                        else
                        {
                            flag2 = false;
                        }
                        num4 = (int)obj2.GetType().GetProperty("Count").GetValue(obj2, null);
                        if (num2 < 0 || num2 >= num4)
                        {
                            goto IL_BB7;
                        }
                        obj = property2.GetValue(obj2, new object[]
                        {
                            num2
                        });
                        if (flag2)
                        {
                            string[] array2 = normalizedPath.Split(new char[]
                            {
                                '.'
                            });
                            array2[num]    = num2.ToString();
                            normalizedPath = string.Join(".", array2);
                        }
                        else
                        {
                            string bestHandleWithIndexForListElement = TranslationHandleUtility.GetBestHandleWithIndexForListElement(obj2, obj);
                            if (!bestHandleWithIndexForListElement.NullOrEmpty())
                            {
                                string[] array3 = suggestedPath.Split(new char[]
                                {
                                    '.'
                                });
                                array3[num]   = bestHandleWithIndexForListElement;
                                suggestedPath = string.Join(".", array3);
                            }
                        }
                    }
                    else
                    {
                        this.loadErrors.Add(string.Concat(new object[]
                        {
                            "Can't enter node ",
                            text2,
                            " at path ",
                            path,
                            ", element kind is ",
                            defInjectionPathPartKind,
                            ". (",
                            fileSource,
                            ")"
                        }));
                    }
                    list.RemoveAt(0);
                    num++;
                }
                bool flag3 = false;
                foreach (KeyValuePair <string, DefInjectionPackage.DefInjection> current in this.injections)
                {
                    if (!(current.Key == path))
                    {
                        if (current.Value.injected && current.Value.normalizedPath == normalizedPath)
                        {
                            string text3 = string.Concat(new string[]
                            {
                                "Duplicate def-injected translation key. Both ",
                                current.Value.path,
                                " and ",
                                path,
                                " refer to the same field (",
                                suggestedPath,
                                ")"
                            });
                            if (current.Value.path != current.Value.nonBackCompatiblePath)
                            {
                                string text4 = text3;
                                text3 = string.Concat(new string[]
                                {
                                    text4,
                                    " (",
                                    current.Value.nonBackCompatiblePath,
                                    " was auto-renamed to ",
                                    current.Value.path,
                                    ")"
                                });
                            }
                            text3 = text3 + " (" + current.Value.fileSource + ")";
                            this.loadErrors.Add(text3);
                            flag3 = true;
                            break;
                        }
                    }
                }
                bool flag4 = false;
                if (!flag3)
                {
                    if (defInjectionPathPartKind == DefInjectionPathPartKind.Field)
                    {
                        FieldInfo fieldNamed = this.GetFieldNamed(obj.GetType(), text2);
                        if (fieldNamed == null)
                        {
                            throw new InvalidOperationException(string.Concat(new object[]
                            {
                                "Field ",
                                text2,
                                " does not exist in type ",
                                obj.GetType(),
                                "."
                            }));
                        }
                        if (fieldNamed.HasAttribute <NoTranslateAttribute>())
                        {
                            this.loadErrors.Add(string.Concat(new object[]
                            {
                                "Translated untranslatable field ",
                                fieldNamed.Name,
                                " of type ",
                                fieldNamed.FieldType,
                                " at path ",
                                path,
                                ". Translating this field will break the game. (",
                                fileSource,
                                ")"
                            }));
                        }
                        else if (fieldNamed.HasAttribute <UnsavedAttribute>())
                        {
                            this.loadErrors.Add(string.Concat(new object[]
                            {
                                "Translated untranslatable field (UnsavedAttribute) ",
                                fieldNamed.Name,
                                " of type ",
                                fieldNamed.FieldType,
                                " at path ",
                                path,
                                ". Translating this field will break the game. (",
                                fileSource,
                                ")"
                            }));
                        }
                        else if (!isPlaceholder && fieldNamed.FieldType != ensureFieldType)
                        {
                            this.loadErrors.Add(string.Concat(new object[]
                            {
                                "Translated non-",
                                ensureFieldType,
                                " field ",
                                fieldNamed.Name,
                                " of type ",
                                fieldNamed.FieldType,
                                " at path ",
                                path,
                                ". Expected ",
                                ensureFieldType,
                                ". (",
                                fileSource,
                                ")"
                            }));
                        }
                        else if (!isPlaceholder && ensureFieldType != typeof(string) && !fieldNamed.HasAttribute <TranslationCanChangeCountAttribute>())
                        {
                            this.loadErrors.Add(string.Concat(new object[]
                            {
                                "Tried to translate field ",
                                fieldNamed.Name,
                                " of type ",
                                fieldNamed.FieldType,
                                " at path ",
                                path,
                                ", but this field doesn't have [TranslationCanChangeCount] attribute so it doesn't allow this type of translation. (",
                                fileSource,
                                ")"
                            }));
                        }
                        else if (!isPlaceholder)
                        {
                            if (ensureFieldType == typeof(string))
                            {
                                replacedString = (string)fieldNamed.GetValue(obj);
                            }
                            else
                            {
                                replacedStringsList = (fieldNamed.GetValue(obj) as IEnumerable <string>);
                            }
                            fieldNamed.SetValue(obj, value);
                            flag4 = true;
                        }
                    }
                    else if (defInjectionPathPartKind == DefInjectionPathPartKind.ListIndex || defInjectionPathPartKind == DefInjectionPathPartKind.ListHandle || defInjectionPathPartKind == DefInjectionPathPartKind.ListHandleWithIndex)
                    {
                        object obj3 = obj;
                        if (obj3 == null)
                        {
                            throw new InvalidOperationException("Tried to use index on null list at " + path);
                        }
                        Type         type      = obj3.GetType();
                        PropertyInfo property3 = type.GetProperty("Count");
                        if (property3 == null)
                        {
                            throw new InvalidOperationException("Tried to use index on non-list (missing 'Count' property).");
                        }
                        if (defInjectionPathPartKind == DefInjectionPathPartKind.ListHandle || defInjectionPathPartKind == DefInjectionPathPartKind.ListHandleWithIndex)
                        {
                            num2 = TranslationHandleUtility.GetElementIndexByHandle(obj3, text2, num2);
                            defInjectionPathPartKind = DefInjectionPathPartKind.ListIndex;
                        }
                        int num5 = (int)property3.GetValue(obj3, null);
                        if (num2 >= num5)
                        {
                            throw new InvalidOperationException(string.Concat(new object[]
                            {
                                "Trying to translate ",
                                defType,
                                ".",
                                path,
                                " at index ",
                                num2,
                                " but the list only has ",
                                num5,
                                " entries (so max index is ",
                                (num5 - 1).ToString(),
                                ")."
                            }));
                        }
                        PropertyInfo property4 = type.GetProperty("Item");
                        if (property4 == null)
                        {
                            throw new InvalidOperationException("Tried to use index on non-list (missing 'Item' property).");
                        }
                        Type propertyType = property4.PropertyType;
                        if (!isPlaceholder && propertyType != ensureFieldType)
                        {
                            this.loadErrors.Add(string.Concat(new object[]
                            {
                                "Translated non-",
                                ensureFieldType,
                                " list item of type ",
                                propertyType,
                                " at path ",
                                path,
                                ". Expected ",
                                ensureFieldType,
                                ". (",
                                fileSource,
                                ")"
                            }));
                        }
                        else if (!isPlaceholder && ensureFieldType != typeof(string) && !flag)
                        {
                            this.loadErrors.Add(string.Concat(new object[]
                            {
                                "Tried to translate field of type ",
                                propertyType,
                                " at path ",
                                path,
                                ", but this field doesn't have [TranslationCanChangeCount] attribute so it doesn't allow this type of translation. (",
                                fileSource,
                                ")"
                            }));
                        }
                        else if (num2 < 0 || num2 >= (int)type.GetProperty("Count").GetValue(obj3, null))
                        {
                            this.loadErrors.Add("Index out of bounds (max index is " + ((int)type.GetProperty("Count").GetValue(obj3, null) - 1) + ")");
                        }
                        else if (!isPlaceholder)
                        {
                            replacedString = (string)property4.GetValue(obj3, new object[]
                            {
                                num2
                            });
                            property4.SetValue(obj3, value, new object[]
                            {
                                num2
                            });
                            flag4 = true;
                        }
                    }
                    else
                    {
                        this.loadErrors.Add(string.Concat(new object[]
                        {
                            "Translated ",
                            text2,
                            " at path ",
                            path,
                            " but it's not a field, it's ",
                            defInjectionPathPartKind,
                            ". (",
                            fileSource,
                            ")"
                        }));
                    }
                }
                if (path != suggestedPath)
                {
                    IList <string> list2 = value as IList <string>;
                    string         text5;
                    if (list2 != null)
                    {
                        text5 = list2.ToStringSafeEnumerable();
                    }
                    else
                    {
                        text5 = value.ToString();
                    }
                    this.loadSyntaxSuggestions.Add(string.Concat(new string[]
                    {
                        "Consider using ",
                        suggestedPath,
                        " instead of ",
                        path,
                        " for translation '",
                        text5,
                        "' (",
                        fileSource,
                        ")"
                    }));
                }
                result = flag4;
                return(result);

Block_41:
                throw new InvalidOperationException("Field " + text2 + " does not exist.");
Block_42:
                throw new InvalidOperationException(string.Concat(new object[]
                {
                    "Translated untranslatable field ",
                    field.Name,
                    " of type ",
                    field.FieldType,
                    " at path ",
                    path,
                    ". Translating this field will break the game."
                }));
Block_43:
                throw new InvalidOperationException(string.Concat(new object[]
                {
                    "Translated untranslatable field ([Unsaved] attribute) ",
                    field.Name,
                    " of type ",
                    field.FieldType,
                    " at path ",
                    path,
                    ". Translating this field will break the game."
                }));
Block_46:
                throw new InvalidOperationException("Tried to use index on non-list (missing 'Item' property).");
IL_ADC:
                throw new InvalidOperationException("Index out of bounds (max index is " + (num3 - 1) + ")");
Block_50:
                throw new InvalidOperationException("Tried to use index on non-list (missing 'Item' property).");
IL_BB7:
                throw new InvalidOperationException("Index out of bounds (max index is " + (num4 - 1) + ")");
            }
            catch (Exception ex)
            {
                string text6 = string.Concat(new object[]
                {
                    "Couldn't inject ",
                    path,
                    " into ",
                    defType,
                    " (",
                    fileSource,
                    "): ",
                    ex.Message
                });
                if (ex.InnerException != null)
                {
                    text6 = text6 + " -> " + ex.InnerException.Message;
                }
                this.loadErrors.Add(text6);
                result = false;
            }
            return(result);
        }
        private static void CleanupDefInjections()
        {
            string        activeLanguageCoreModFolderPath = TranslationFilesCleaner.GetActiveLanguageCoreModFolderPath();
            string        text          = Path.Combine(activeLanguageCoreModFolderPath, "DefLinked");
            string        text2         = Path.Combine(activeLanguageCoreModFolderPath, "DefInjected");
            DirectoryInfo directoryInfo = new DirectoryInfo(text);

            if (directoryInfo.Exists)
            {
                if (!Directory.Exists(text2))
                {
                    Directory.Move(text, text2);
                    Thread.Sleep(1000);
                    directoryInfo = new DirectoryInfo(text2);
                }
            }
            else
            {
                directoryInfo = new DirectoryInfo(text2);
            }
            if (!directoryInfo.Exists)
            {
                Log.Error("Could not find def-injections folder for the active language.", false);
                return;
            }
            FileInfo[] files = directoryInfo.GetFiles("*.xml", SearchOption.AllDirectories);
            for (int i = 0; i < files.Length; i++)
            {
                FileInfo fileInfo = files[i];
                try
                {
                    fileInfo.Delete();
                }
                catch (Exception ex)
                {
                    Log.Error(string.Concat(new object[]
                    {
                        "Could not delete ",
                        fileInfo.Name,
                        ": ",
                        ex
                    }), false);
                }
            }
            foreach (Type current in GenDefDatabase.AllDefTypesWithDatabases())
            {
                try
                {
                    TranslationFilesCleaner.CleanupDefInjectionsForDefType(current, directoryInfo.FullName);
                }
                catch (Exception ex2)
                {
                    Log.Error(string.Concat(new object[]
                    {
                        "Could not process def-injections for type ",
                        current.Name,
                        ": ",
                        ex2
                    }), false);
                }
            }
        }