Inheritance: IDisposable
Esempio n. 1
0
        private void aliasContextMenuDuplicate_Click(object sender, EventArgs e)
        {
            TreeNode selectedNode     = treeView.SelectedNode;
            FileData selectedFileData = ModuleDataManager.GetInstance().GetSelectedFileData(treeView.SelectedNode);

            if (selectedFileData == null)
            {
                return;
            }

            IModuleFileData moduleFile = selectedFileData as IModuleFileData;

            if (moduleFile == null)
            {
                return; // Don't know how to clone something not module file data
            }

            // Get the correct type from any descendant nodes (including grandchildren)
            string             manifestEntryType = selectedNode.FullPath.Split('\\')[1];
            string             sourceModName     = selectedNode.FullPath.Split('\\')[0];
            ModuleFile         sourceModule      = moduleFile.GetModuleFile();
            string             uri      = sourceModule != null ? sourceModule.FullAlias : selectedFileData.FileName;
            CloneAliasCallback callback = new CloneAliasCallback(this, selectedFileData, manifestEntryType);
            CloneDialog        dialog   = new CloneDialog(uri, selectedFileData.GetNameForCloning(), sourceModName);

            dialog.SetCallback(callback);
            dialog.ShowDialog();
        }
        public HashSet <string> PreviewCloneDependencies(ModuleFile module, CloneObjectParameters cloneParameters)
        {
            HashSet <string> alreadyCloned = new HashSet <string>();

            module.Clone(cloneParameters, alreadyCloned, false);
            return(alreadyCloned);
        }
Esempio n. 3
0
        private string GetAliasOrFlatName()
        {
            ModuleFile moduleFile = GetModuleFile();
            string     flatPath   = Path.Replace(ModuleDataManager.GetInstance().ModsDirectoryPath, "");

            return((moduleFile != null) ? moduleFile.FullAlias : flatPath);
        }
Esempio n. 4
0
        private void treeView_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (e.Label != null && e.Label.Length > 0)
            {
                FileData        fileData       = e.Node.Tag as FileData;
                IModuleFileData moduleFileData = e.Node.Tag as IModuleFileData;
                ModuleFile      moduleFile     = moduleFileData.GetModuleFile();
                string          oldAlias       = moduleFile.FullAlias;
                Module          mod            = moduleFile.Module;
                string          newAlias       = mod.Name + ":" + e.Label;

                // Update the references to use the new alias.
                foreach (FileData reference in fileData.ReferencedByFileData.Values)
                {
                    if (reference.FlatFileData != null)
                    {
                        string updatedFlatFile = reference.FlatFileData.Replace(oldAlias, newAlias);
                        reference.TrySetFlatFileData(updatedFlatFile);
                        reference.TrySaveFile();
                    }
                }

                mod.AddToManifest(e.Label, moduleFile.OriginalPath);
                mod.RemoveFromManifest("aliases", moduleFile.Alias);
                mod.WriteManifestToFile();
                Reload();
            }
            else
            {
                e.CancelEdit = true;
            }
        }
Esempio n. 5
0
        private void AddModuleFiles(string fileType, string jsonKey)
        {
            JToken fileTypes = mManifestJson[jsonKey];

            if (fileTypes != null)
            {
                Dictionary <string, ModuleFile> dictionary;
                if (mModuleFiles.ContainsKey(fileType))
                {
                    dictionary = mModuleFiles[fileType];
                }
                else
                {
                    dictionary             = new Dictionary <string, ModuleFile>();
                    mModuleFiles[fileType] = dictionary;
                }

                foreach (JToken item in fileTypes.Children())
                {
                    JProperty alias = item as JProperty;
                    string    name  = alias.Name.Trim();
                    string    value = alias.Value.ToString().Trim();

                    ModuleFile moduleFile = new ModuleFile(this, name, value);
                    moduleFile.IsDeprecated = IsAliasDeprecated(name);
                    dictionary.Add(name, moduleFile);
                }
            }
        }
Esempio n. 6
0
        private bool CanAddFineVersion(FileData file)
        {
            JsonFileData jsonFileData = file as JsonFileData;

            if (jsonFileData == null)
            {
                return(false); // Don't know how to clone something not jsonFileData
            }

            ModuleFile moduleFile = jsonFileData.GetModuleFile();

            if (moduleFile == null || moduleFile.IsFineVersion || jsonFileData.JsonType != JSONTYPE.ENTITY)
            {
                return(false); // can only make fine version of a module file
            }

            string fineFullAlias = moduleFile.FullAlias + ":fine";

            if (ModuleDataManager.GetInstance().GetModuleFile(fineFullAlias) != null)
            {
                return(false); // fine already exists
            }

            return(true);
        }
Esempio n. 7
0
        public override bool UpdateTreeNode(TreeNode node, string filter)
        {
            base.UpdateTreeNode(node, filter);
            mTreeNode = node;
            node.Tag  = this;
            bool       filterMatchesSelf = true;
            ModuleFile owner             = GetModuleFile();

            if (!string.IsNullOrEmpty(filter) && owner != null && !owner.Alias.Contains(filter))
            {
                filterMatchesSelf = false;
            }

            if (!HasErrors)
            {
                node.SelectedImageIndex = 1;
                node.ImageIndex         = 1;
            }

            if (!filterMatchesSelf)
            {
                if (!filter.Contains("error") || !HasErrors)
                {
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 8
0
        private string GetAliasOrFlatName()
        {
            ModuleFile moduleFile = GetModuleFile();
            string     flatPath   = ModuleDataManager.GetInstance().TryReplaceModsDirectory(Path, "", "");

            flatPath = ModuleDataManager.GetInstance().TryReplaceSteamUploadsDirectory(flatPath, "", "");
            return((moduleFile != null) ? moduleFile.FullAlias : flatPath);
        }
Esempio n. 9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="newPath"></param>
        /// <param name="oldName"></param>
        /// <param name="newFileName"></param>
        /// <param name="alreadyCloned"></param>
        /// <param name="execute">whether to actual execute the clone. otherwise, this is just a preview</param>
        /// <returns></returns>
        public virtual bool Clone(string newPath, CloneObjectParameters parameters, HashSet <string> alreadyCloned, bool execute)
        {
            // Ensure directory exists
            string directory = System.IO.Path.GetDirectoryName(newPath);

            alreadyCloned.Add(newPath);
            if (execute)
            {
                System.IO.Directory.CreateDirectory(directory);
            }

            // Figure out what dependency files need to exist
            foreach (KeyValuePair <string, FileData> dependencyKV in GetDependencies())
            {
                string   dependencyName = dependencyKV.Key;
                FileData dependencyFile = dependencyKV.Value;
                if (dependencyFile != null && ShouldCloneDependency(dependencyName, parameters))
                {
                    // We want to clone this dependency
                    IModuleFileData modFileData = dependencyFile as IModuleFileData;
                    if (modFileData != null && modFileData.GetModuleFile() != null)
                    {
                        // This dependency is an alias. Clone the alias.
                        ModuleFile linkedAlias  = modFileData.GetModuleFile();
                        string     aliasNewName = parameters.TransformAlias(dependencyName);
                        if (!alreadyCloned.Contains(aliasNewName))
                        {
                            alreadyCloned.Add(aliasNewName);
                            linkedAlias.Clone(parameters, alreadyCloned, execute);
                        }
                    }
                    else
                    {
                        // This dependency is just a FileData, clone the fileData.
                        string transformedDependencyName = parameters.TransformModPath(dependencyName);
                        string newDependencyPath         = ModuleDataManager.GetInstance().GetMod(parameters.TargetModule).ParentDirectory + parameters.TransformParameter(transformedDependencyName);
                        if (!alreadyCloned.Contains(newDependencyPath))
                        {
                            alreadyCloned.Add(newDependencyPath);
                            dependencyFile.Clone(newDependencyPath, parameters, alreadyCloned, execute);
                        }
                    }
                }
            }

            if (execute)
            {
                string flatFileData = ResolveLocalizedStrings(parameters, FlatFileData);
                string newFlatFile  = parameters.TransformParameter(flatFileData);

                using (StreamWriter wr = new StreamWriter(newPath, false, new UTF8Encoding(false)))
                {
                    wr.Write(newFlatFile);
                }
            }

            return(true);
        }
Esempio n. 10
0
        // Returns true if should show parent node
        public override bool UpdateTreeNode(TreeNode node, string filter)
        {
            base.UpdateTreeNode(node, filter);
            mTreeNode = node;
            node.Tag  = this;

            if (!HasErrors)
            {
                node.SelectedImageIndex = (int)JsonType;
                node.ImageIndex         = (int)JsonType;
            }

            bool       filterMatchesSelf = true;
            ModuleFile owner             = GetModuleFile();

            if (!string.IsNullOrEmpty(filter) && owner != null && !owner.Alias.Contains(filter))
            {
                filterMatchesSelf = false;
            }

            bool hasChildMatchingFilter = false;

            if (JsonType == JSONTYPE.JOB)
            {
                if (OpenedFiles.Count > 1)
                {
                    FileData recipeJsonData = OpenedFiles[1];
                    TreeNode recipes        = new TreeNode(recipeJsonData.FileName);
                    recipeJsonData.UpdateTreeNode(recipes, filter);

                    IOrderedEnumerable <KeyValuePair <string, FileData> > sortedRecipes = recipeJsonData.LinkedFileData.OrderBy(recipe => recipe.Key);
                    foreach (KeyValuePair <string, FileData> recipe in sortedRecipes)
                    {
                        string recipePath = recipe.Key;
                        string recipeName = System.IO.Path.GetFileNameWithoutExtension(recipePath);
                        if (string.IsNullOrEmpty(filter) || recipeName.Contains(filter) || filterMatchesSelf)
                        {
                            TreeNode recipeNode = new TreeNode(recipeName);
                            recipe.Value.UpdateTreeNode(recipeNode, filter);
                            recipes.Nodes.Add(recipeNode);
                            hasChildMatchingFilter = true;
                        }
                    }

                    node.Nodes.Add(recipes);
                }
            }

            if (!hasChildMatchingFilter && !filterMatchesSelf)
            {
                if (!filter.Contains("error") || !HasErrors)
                {
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 11
0
        public ModuleFile GetModuleFile(string fileType, string alias)
        {
            ModuleFile returned = null;

            if (mModuleFiles.ContainsKey(fileType))
            {
                mModuleFiles[fileType].TryGetValue(alias, out returned);
            }

            return(returned);
        }
        public bool ExecuteClone(FileData file, CloneObjectParameters parameters, HashSet <string> unwantedItems)
        {
            ModuleFile owningFile = (file as IModuleFileData).GetModuleFile();

            if (owningFile != null)
            {
                return(ExecuteClone(owningFile, parameters, unwantedItems));
            }

            string newPath = parameters.TransformParameter(file.Path);

            return(file.Clone(newPath, parameters, unwantedItems, true));
        }
Esempio n. 13
0
        /// <summary>
        /// Tries to convert a string to an (openable) file
        /// </summary>
        /// <param name="text"></param>
        /// <param name="module"></param>
        /// <returns></returns>
        private bool tryGetModuleFile(string text, out ModuleFile module)
        {
            module = null;

            // Simple check
            if (text.StartsWith("i18n("))
            {
                return(false);
            }

            var parent = System.IO.Path.GetDirectoryName(this.mFileData.Path);

            return(ModuleDataManager.GetInstance().TryGetModuleFile(text, parent, out module));
        }
Esempio n. 14
0
        private void removeFromManifestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode   selectedNode     = treeView.SelectedNode;
            FileData   selectedFileData = ModuleDataManager.GetInstance().GetSelectedFileData(treeView.SelectedNode);
            ModuleFile moduleFile       = GetModuleFile(selectedFileData);

            if (moduleFile != null)
            {
                TreeNode parent = selectedNode.Parent;
                moduleFile.Module.RemoveFromManifest(parent.Text, moduleFile.Alias);
                moduleFile.Module.WriteManifestToFile();
                Reload();
            }
        }
        public HashSet <string> PreviewCloneDependencies(FileData file, CloneObjectParameters cloneParameters)
        {
            ModuleFile owningFile = (file as IModuleFileData).GetModuleFile();

            if (owningFile != null)
            {
                return(PreviewCloneDependencies(owningFile, cloneParameters));
            }

            HashSet <string> alreadyCloned = new HashSet <string>();
            string           newPath       = cloneParameters.TransformParameter(file.Path);

            file.Clone(newPath, cloneParameters, alreadyCloned, false);
            return(alreadyCloned);
        }
Esempio n. 16
0
        public void Load()
        {
            ParseGenericEncounterScripts(MainForm.kModsDirectoryPath + "/stonehearth/services/server/game_master/controllers");

            // get the game master index location
            foreach (Module module in ModuleDataManager.GetInstance().GetAllModules())
            {
                ModuleFile gmIndex = module.GetAliasFile("data:gm_index");
                if (gmIndex != null)
                {
                    string folder = JsonHelper.NormalizeSystemPath(System.IO.Path.GetDirectoryName(gmIndex.ResolvedPath));
                    ParseEncounterScripts(module.Name, folder);
                    ParseNodeGraph(module.Name, folder);
                }
            }
        }
Esempio n. 17
0
        private void ParseLinkedAliases(string jsonString)
        {
            Regex matcher = new Regex("\"([A-z|_|-]+\\:[\\S]*)\"");

            foreach (Match match in matcher.Matches(jsonString))
            {
                string     fullAlias   = match.Groups[1].Value;
                ModuleFile linkedAlias = ModuleDataManager.GetInstance().GetModuleFile(fullAlias);
                if (linkedAlias == null)
                {
                    continue;
                }

                LinkedAliases.Add(linkedAlias);
                linkedAlias.AddReference(GetAliasOrFlatName(), this);
            }
        }
        public FileData GetSelectedFileData(string selected)
        {
            string[] path = selected.Split('\\');
            if (path.Length <= 2)
            {
                return(null);
            }

            Module     module = mModules[path[0]];
            ModuleFile file   = module.GetModuleFile(path[1], path[2]);

            if (file != null)
            {
                return(file.GetFileData(path));
            }

            return(null);
        }
        public HashSet <string> PreviewCloneDependencies(FileData file, CloneObjectParameters cloneParameters)
        {
            ModuleFile owningFile = (file as IModuleFileData).GetModuleFile();

            if (owningFile != null)
            {
                return(PreviewCloneDependencies(owningFile, cloneParameters));
            }

            HashSet <string> alreadyCloned = new HashSet <string>();
            string           newPath       = TransformPath(file.Path, cloneParameters);

            // Code will only get here if owningFile is null, so calling the below will cause a null ref exception when indexing the owningFile
            // .Replace(owningFile.Module.Name, cloneParameters.TargetModule);

            file.Clone(newPath, cloneParameters, alreadyCloned, false);
            return(alreadyCloned);
        }
        /// <summary>
        /// Attempts to resolve a reference.
        /// </summary>
        /// <param name="path">Reference that was given</param>
        /// <param name="parentDirectory">Parent directory, required to resolve relative paths.</param>
        /// <param name="moduleFile">The file that was found.</param>
        /// <returns><c>true</c> if the file was found, <c>false</c> otherwise.</returns>
        public bool TryGetModuleFile(string path, string parentDirectory, out ModuleFile moduleFile)
        {
            moduleFile = null;

            // Alias?
            if (path.Contains(":"))
            {
                moduleFile = this.GetModuleFile(path);
                return(true);
            }
            else
            {
                var fileName = JsonHelper.GetFileFromFileJson(path, parentDirectory);

                // Is it a valid filename?
                if (!File.Exists(fileName))
                {
                    return(false); // Not a valid file => we don't stand a chance to begin with
                }
                // Cut away the unrequired bits
                string temp = ModuleDataManager.GetInstance().TryReplaceModsDirectory(fileName, "", "");
                temp = ModuleDataManager.GetInstance().TryReplaceSteamUploadsDirectory(temp, "", "");
                temp = temp.TrimStart(System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar);
                var simplifiedFileName = temp;

                // Split it into mod/path within mod
                var parts = simplifiedFileName.Split(new[] { System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar }, 2);

                var mod = ModuleDataManager.GetInstance().GetMod(parts[0]);

                if (mod == null)
                {
                    return(false);
                }

                // The file exists, but isn't a global alias, so create a temporary entry so the caller can access it.
                moduleFile = new ModuleFile(mod, "<no-alias>", parts[1]);
                return(true);

                ////// Get all aliases that match this file
                ////var aliases = mod.GetAliases().Where(alias => alias.ResolvedPath == fileName).ToList();
                ////return null;
            }
        }
Esempio n. 21
0
        public bool Clone(CloneObjectParameters parameters, HashSet <string> alreadyCloned, bool execute)
        {
            string newAlias      = parameters.TransformAlias(mAlias);
            string sourceModName = Module.Name;
            string targetModName = parameters.TargetModule == null ? sourceModName : parameters.TargetModule;
            Module targetModule  = ModuleDataManager.GetInstance().GetMod(targetModName);

            if (targetModule.GetAliasFile(newAlias) != null)
            {
                // MessageBox.Show("The alias " + newAlias + " already exists in manifest.json");
                return(false);
            }

            string modPath      = targetModule.ParentDirectory;
            string relativePath = ResolvedPath.Replace(mModule.Path + "/", "");
            string newPath      = parameters.TransformParameter(relativePath);
            string fullPath     = modPath + "/" + targetModName + "/" + newPath;

            if (!FileData.Clone(fullPath, parameters, alreadyCloned, execute))
            {
                return(false);
            }

            alreadyCloned.Add(targetModName + ':' + newAlias);
            if (execute)
            {
                string     fileLocation = "file(" + newPath + ")";
                ModuleFile file         = new ModuleFile(targetModule, newAlias, fileLocation);
                file.TryLoad();
                if (file.FileData != null)
                {
                    targetModule.AddToManifest(newAlias, fileLocation, parameters.manifestEntryType);
                    targetModule.WriteManifestToFile();
                    return(true);
                }
            }
            else
            {
                return(true);
            }

            return(false);
        }
Esempio n. 22
0
        private void AddModuleFiles(string fileType)
        {
            JToken fileTypes = mManifestJson[fileType];

            if (fileTypes != null)
            {
                Dictionary <string, ModuleFile> dictionary = new Dictionary <string, ModuleFile>();
                mModuleFiles[fileType] = dictionary;
                foreach (JToken item in fileTypes.Children())
                {
                    JProperty alias = item as JProperty;
                    string    name  = alias.Name.Trim();
                    string    value = alias.Value.ToString().Trim();

                    ModuleFile moduleFile = new ModuleFile(this, name, value);
                    dictionary.Add(name, moduleFile);
                }
            }
        }
        public FileData GetSelectedFileData(string selected)
        {
            // FullPath is a property of treeviews that consists of the labels of all of the
            // tree nodes that must be navigated to reach the selected tree node
            string[] path = selected.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);

            if (path.Length <= 2 || !mModules.ContainsKey(path[0]))
            {
                return(null);
            }

            Module     module = mModules[path[0]];
            ModuleFile file   = module.GetModuleFile(path[1], path[2]);

            if (file != null)
            {
                return(file.GetFileData(path));
            }

            return(null);
        }
Esempio n. 24
0
        private void makeFineVersionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode selectedNode     = treeView.SelectedNode;
            FileData selectedFileData = ModuleDataManager.GetInstance().GetSelectedFileData(treeView.SelectedNode);

            if (!CanAddFineVersion(selectedFileData))
            {
                return;
            }

            JsonFileData          jsonFileData = selectedFileData as JsonFileData;
            ModuleFile            moduleFile   = jsonFileData.GetModuleFile();
            CloneObjectParameters parameters   = new CloneObjectParameters();

            parameters.AddStringReplacement(moduleFile.ShortName, moduleFile.ShortName + "_fine");
            parameters.AddAliasReplacement(moduleFile.ShortName + "_fine", moduleFile.ShortName + ":fine");
            HashSet <string>          dependencies = ModuleDataManager.GetInstance().PreviewCloneDependencies(selectedFileData, parameters);
            PreviewCloneAliasCallback callback     = new PreviewCloneAliasCallback(this, selectedFileData, parameters);
            PreviewCloneDialog        dialog       = new PreviewCloneDialog("Creating " + moduleFile.ShortName + ":fine", dependencies, callback);

            dialog.ShowDialog();
        }
        public void Load()
        {
            ParseGenericEncounterScripts(MainForm.kModsDirectoryPath + "/stonehearth/services/server/game_master/controllers");
            var defaultSchemaPath = Application.StartupPath + "/schemas/encounters/encounter.json";

            using (StreamReader sr = new StreamReader(defaultSchemaPath, System.Text.Encoding.UTF8))
            {
                mDefaultSchema = JsonSchemaTools.ParseSchema(sr.ReadToEnd(), defaultSchemaPath);
            }

            // get the game master index location
            foreach (Module module in ModuleDataManager.GetInstance().GetAllModules())
            {
                ModuleFile gmIndex = module.GetAliasFile("data:gm_index");
                if (gmIndex != null)
                {
                    string folder = JsonHelper.NormalizeSystemPath(System.IO.Path.GetDirectoryName(gmIndex.ResolvedPath));
                    ParseEncounterScripts(module.Name, folder);
                    ParseNodeGraph(module.Name, folder);
                }
            }
        }
Esempio n. 26
0
        public bool Clone(CloneObjectParameters parameters, HashSet <string> alreadyCloned, bool execute)
        {
            string newAlias = parameters.TransformAlias(mAlias);

            if (mModule.GetAliasFile(newAlias) != null)
            {
                // MessageBox.Show("The alias " + newAlias + " already exists in manifest.json");
                return(false);
            }

            string newPath = parameters.TransformParameter(ResolvedPath);

            if (!FileData.Clone(newPath, parameters, alreadyCloned, execute))
            {
                return(false);
            }

            alreadyCloned.Add(mModule.Name + ':' + newAlias);
            if (execute)
            {
                string     fileLocation = "file(" + newPath.Replace(mModule.Path + "/", "") + ")";
                ModuleFile file         = new ModuleFile(Module, newAlias, fileLocation);
                file.TryLoad();
                if (file.FileData != null)
                {
                    mModule.AddToManifest(newAlias, fileLocation);
                    mModule.WriteManifestToFile();
                    return(true);
                }
            }
            else
            {
                return(true);
            }

            return(false);
        }
Esempio n. 27
0
        private void dependenciesListBox_DoubleClick(object sender, EventArgs e)
        {
            if (mSelectedFileData == null)
            {
                return;
            }

            ListBox listBox      = sender as ListBox;
            string  selectedItem = (string)listBox.SelectedItem;

            if (selectedItem == null)
            {
                return;
            }

            if (selectedItem.Contains(":"))
            {
                // item is a alias item. we should navigate there.
                ModuleFile file = ModuleDataManager.GetInstance().GetModuleFile(selectedItem);
                if (file != null)
                {
                    SetSelectedFileData(file.FileData);
                }
            }
            else
            {
                string fileName  = System.IO.Path.GetFileNameWithoutExtension(selectedItem);
                bool   foundFile = false;
                foreach (TabPage tabPage in filePreviewTabs.TabPages)
                {
                    string tabName = tabPage.Text.Replace("*", "").Trim();
                    if (tabName.Equals(fileName))
                    {
                        filePreviewTabs.SelectedTab = tabPage;
                        foundFile = true;
                        break;
                    }
                }

                if (!foundFile)
                {
                    FileData data;
                    bool     hasFileData = false;
                    if (mSelectedFileData.ReferencedByFileData.TryGetValue(selectedItem, out data))
                    {
                        hasFileData = true;
                    }

                    string fullPath = ModuleDataManager.GetInstance().ModsDirectoryPath + selectedItem;
                    if (!hasFileData && mSelectedFileData.LinkedFileData.TryGetValue(fullPath, out data))
                    {
                        hasFileData = true;
                    }

                    if (hasFileData)
                    {
                        SetSelectedFileData(data);
                        if (data.TreeNode != null)
                        {
                            treeView.SelectedNode = data.TreeNode;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Tries to convert a string to an (openable) file
        /// </summary>
        /// <param name="text"></param>
        /// <param name="module"></param>
        /// <returns></returns>
        private bool tryGetModuleFile(string text, out ModuleFile module)
        {
            module = null;

            // Simple checks
            if (text.StartsWith("i18n(") || text.IndexOfAny(new[] { ':', '/' }) == -1)
                return false;

            var parent = System.IO.Path.GetDirectoryName(this.mFileData.Path);
            return ModuleDataManager.GetInstance().TryGetModuleFile(text, parent, out module);
        }
 public void SetModuleFile(ModuleFile moduleFile)
 {
     mOwner = moduleFile;
 }
Esempio n. 30
0
        private void PopulateFileDetails(GameMasterNode node)
        {
            fileDetailsListBox.Items.Clear();
            if (node == null)
            {
                return;
            }

            Dictionary <string, float> stats = new Dictionary <string, float>();

            if (node.NodeType == GameMasterNodeType.ENCOUNTER)
            {
                EncounterNodeData encounterData = node.NodeData as EncounterNodeData;
                if (encounterData.EncounterType == "create_mission" || encounterData.EncounterType == "city_raid")
                {
                    JToken members = node.Json.SelectToken("create_mission_info.mission.members");

                    if (members == null)
                    {
                        JToken missions = node.Json.SelectToken("city_raid_info.missions");
                        foreach (JProperty content in missions.Children())
                        {
                            // Only gets stats for the first mission of city raids
                            members = content.Value["members"];
                        }
                    }

                    int   maxEnemies            = 0;
                    float totalWeaponBaseDamage = 0;

                    Dictionary <string, float> allStats = new Dictionary <string, float>();
                    foreach (string attribute in kAttributesOfInterest)
                    {
                        allStats[attribute] = 0;
                    }

                    if (members != null)
                    {
                        foreach (JToken member in members.Children())
                        {
                            // grab name, max number of members, and tuning
                            JProperty memberProperty = member as JProperty;
                            if (memberProperty != null)
                            {
                                JValue jMax = memberProperty.Value.SelectToken("from_population.max") as JValue;
                                int    max  = 0;
                                if (jMax != null)
                                {
                                    max        = jMax.Value <int>();
                                    maxEnemies = maxEnemies + max;
                                }

                                JValue tuning = memberProperty.Value.SelectToken("tuning") as JValue;
                                if (tuning != null)
                                {
                                    string     alias      = tuning.ToString();
                                    ModuleFile tuningFile = ModuleDataManager.GetInstance().GetModuleFile(alias);
                                    if (tuningFile != null)
                                    {
                                        JsonFileData jsonFileData = tuningFile.FileData as JsonFileData;
                                        if (jsonFileData != null)
                                        {
                                            foreach (string attribute in kAttributesOfInterest)
                                            {
                                                JValue jAttribute = jsonFileData.Json.SelectToken("attributes." + attribute) as JValue;
                                                if (jAttribute != null)
                                                {
                                                    allStats[attribute] = allStats[attribute] + (max * jAttribute.Value <int>());
                                                }
                                            }

                                            JArray weapon = jsonFileData.Json.SelectToken("equipment.weapon") as JArray;
                                            if (weapon != null)
                                            {
                                                foreach (JValue weaponAlias in weapon.Children())
                                                {
                                                    ModuleFile weaponModuleFile = ModuleDataManager.GetInstance().GetModuleFile(weaponAlias.ToString());
                                                    if (weaponModuleFile != null)
                                                    {
                                                        JToken baseDamage = (weaponModuleFile.FileData as JsonFileData).Json.SelectToken("entity_data.stonehearth:combat:weapon_data.base_damage");
                                                        if (baseDamage != null)
                                                        {
                                                            totalWeaponBaseDamage = totalWeaponBaseDamage + (max * baseDamage.Value <int>());
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    fileDetailsListBox.Items.Add("max enemies : " + maxEnemies);
                    fileDetailsListBox.Items.Add("total weapon damage : " + totalWeaponBaseDamage);
                    foreach (string attribute in kAttributesOfInterest)
                    {
                        fileDetailsListBox.Items.Add("total " + attribute + " : " + allStats[attribute]);
                    }

                    fileDetailsListBox.Items.Add("average weapon damage : " + totalWeaponBaseDamage / maxEnemies);

                    foreach (string attribute in kAttributesOfInterest)
                    {
                        fileDetailsListBox.Items.Add("average " + attribute + " : " + allStats[attribute] / maxEnemies);
                    }
                }
            }
        }
 // Call to clone an alias. top level. nested clone calls should call the module directly.
 public bool ExecuteClone(ModuleFile module, CloneObjectParameters parameters, HashSet<string> unwantedItems)
 {
     return module.Clone(parameters, unwantedItems, true);
 }
Esempio n. 32
0
        private void ParseJsonSpecificData()
        {
            string directory = Directory;

            switch (mJsonType)
            {
            case JSONTYPE.ENTITY:
                JToken entityFormsComponent = mJson.SelectToken("components.stonehearth:entity_forms");
                if (entityFormsComponent != null)
                {
                    // Look for stonehearth:entity_forms
                    JToken ghostForm = entityFormsComponent["ghost_form"];
                    if (ghostForm != null)
                    {
                        string ghostFilePath = JsonHelper.GetFileFromFileJson(ghostForm.ToString(), directory);
                        ghostFilePath = JsonHelper.NormalizeSystemPath(ghostFilePath);
                        JsonFileData ghost = new JsonFileData(ghostFilePath);
                        ghost.Load();
                        ghost.AddMixin("stonehearth:mixins:placed_object");
                        OpenedFiles.Add(ghost);
                        ghost.PostLoad();
                    }

                    JToken iconicForm = entityFormsComponent["iconic_form"];
                    if (iconicForm != null)
                    {
                        string iconicFilePath = JsonHelper.GetFileFromFileJson(iconicForm.ToString(), directory);
                        iconicFilePath = JsonHelper.NormalizeSystemPath(iconicFilePath);
                        JsonFileData iconic = new JsonFileData(iconicFilePath);
                        iconic.Load();
                        OpenedFiles.Add(iconic);
                    }

                    CheckForNoNetWorth();
                }
                else
                {
                    if (GetModuleFile() != null && mJson.SelectToken("components.item") != null)
                    {
                        CheckForNoNetWorth();
                    }
                }

                break;

            case JSONTYPE.JOB:
                // Parse crafter stuff
                JToken crafter = mJson["crafter"];
                if (crafter != null)
                {
                    // This is a crafter, load its recipes
                    string recipeListLocation = crafter["recipe_list"].ToString();
                    recipeListLocation = JsonHelper.GetFileFromFileJson(recipeListLocation, directory);
                    JsonFileData recipes = new JsonFileData(recipeListLocation);
                    recipes.Load();
                    foreach (FileData recipe in recipes.LinkedFileData.Values)
                    {
                        recipes.RelatedFiles.Add(recipe);
                    }

                    OpenedFiles.Add(recipes);
                    recipes.ReferencedByFileData[GetAliasOrFlatName()] = this;
                }

                JObject jobEquipment = mJson["equipment"] as JObject;
                if (jobEquipment != null)
                {
                    foreach (JToken equippedItem in jobEquipment.Children())
                    {
                        string   equipmentJson = equippedItem.Last.ToString();
                        FileData fileData      = null;
                        if (equipmentJson.IndexOf(':') >= 0)
                        {
                            foreach (ModuleFile alias in LinkedAliases)
                            {
                                if (alias.FullAlias.Equals(equipmentJson))
                                {
                                    fileData = alias.FileData;
                                }
                            }
                        }
                        else
                        {
                            equipmentJson = JsonHelper.GetFileFromFileJson(equipmentJson, directory);
                            LinkedFileData.TryGetValue(equipmentJson, out fileData);
                        }

                        JsonFileData jsonFileData = fileData as JsonFileData;
                        if (jsonFileData != null)
                        {
                            JToken equipment_piece = jsonFileData.mJson.SelectToken("components.stonehearth:equipment_piece");
                            if (equipment_piece != null)
                            {
                                JToken ilevel = equipment_piece["ilevel"];
                                if (ilevel != null && ilevel.Value <int>() > 0)
                                {
                                    JToken noDrop = equipment_piece["no_drop"];
                                    if (noDrop == null || !noDrop.Value <bool>())
                                    {
                                        AddError("Equipment piece " + equipmentJson + " is not set to no_drop=true even through it is a job equipment!");
                                    }
                                }
                            }
                        }
                    }
                }

                ////AlterJobExperience();
                break;

            case JSONTYPE.RECIPE:
                JToken portrait = mJson["portrait"];
                if (portrait != null)
                {
                    string portraitImageLocation = portrait.ToString();
                    portraitImageLocation = JsonHelper.GetFileFromFileJson(portraitImageLocation, directory);
                    ImageFileData image = new ImageFileData(portraitImageLocation);
                    LinkedFileData.Add(portraitImageLocation, image);
                }

                break;

            case JSONTYPE.AI_PACK:
                JArray actions = mJson["actions"] as JArray;
                if (actions != null)
                {
                    foreach (JToken action in actions)
                    {
                        string     fullAlias   = action.ToString();
                        ModuleFile linkedAlias = ModuleDataManager.GetInstance().GetModuleFile(fullAlias);
                        if (linkedAlias == null)
                        {
                            AddError("links to alias " + fullAlias + " which does not exist!");
                        }
                    }
                }
                break;

            case JSONTYPE.MONSTER_TUNING:
                JToken experience = mJson.SelectToken("attributes.exp_reward");
                if (experience != null)
                {
                    //Console.WriteLine(GetAliasOrFlatName() + "\t" + experience.ToString());
                }
                break;
            }

            CheckDisplayName();
            if (Json != null && Json.SelectToken("components.effect_list.effects") != null)
            {
                AddError("effect_list component is using 'effects' to specify a list of effects. This is bad because these effects will not restart after save load. You should put all the effects into a single file and reference that file as 'default'");
            }

            FixUpAllCombatData();
        }
Esempio n. 33
0
 public void SetModuleFile(ModuleFile moduleFile)
 {
     mOwner = moduleFile;
 }
 public HashSet<string> PreviewCloneDependencies(ModuleFile module, CloneObjectParameters cloneParameters)
 {
     HashSet<string> alreadyCloned = new HashSet<string>();
     module.Clone(cloneParameters, alreadyCloned, false);
     return alreadyCloned;
 }
        /// <summary>
        /// Attempts to resolve a reference.
        /// </summary>
        /// <param name="path">Reference that was given</param>
        /// <param name="parentDirectory">Parent directory, required to resolve relative paths.</param>
        /// <param name="moduleFile">The file that was found.</param>
        /// <returns><c>true</c> if the file was found, <c>false</c> otherwise.</returns>
        public bool TryGetModuleFile(string path, string parentDirectory, out ModuleFile moduleFile)
        {
            moduleFile = null;

            // Alias?
            if (path.Contains(":"))
            {
                moduleFile = this.GetModuleFile(path);
                return true;
            }
            else
            {
                var fileName = JsonHelper.GetFileFromFileJson(path, parentDirectory);

                // Is it a valid filename?
                if (!File.Exists(fileName))
                    return false; // Not a valid file => we don't stand a chance to begin with

                // Cut away the unrequired bits
                var simplifiedFileName = fileName.Replace(ModuleDataManager.GetInstance().ModsDirectoryPath, "").TrimStart(System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar);

                // Split it into mod/path within mod
                var parts = simplifiedFileName.Split(new[] { System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar }, 2);

                var mod = ModuleDataManager.GetInstance().GetMod(parts[0]);

                if (mod == null)
                    return false;

                // The file exists, but we can't say much beyond that.
                return true;

                ////// Get all aliases that match this file
                ////var aliases = mod.GetAliases().Where(alias => alias.ResolvedPath == fileName).ToList();
                ////return null;
            }
        }
Esempio n. 36
0
        public bool Clone(CloneObjectParameters parameters, HashSet<string> alreadyCloned, bool execute)
        {
            string newAlias = parameters.TransformAlias(mAlias);
            string sourceModName = Module.Name;
            string targetModName = parameters.TargetModule == null ? sourceModName : parameters.TargetModule;
            Module targetModule = ModuleDataManager.GetInstance().GetMod(targetModName);

            if (targetModule.GetAliasFile(newAlias) != null)
            {
                // MessageBox.Show("The alias " + newAlias + " already exists in manifest.json");
                return false;
            }

            string newPath = parameters.TransformParameter(ResolvedPath.Replace(sourceModName, targetModName));
            if (!FileData.Clone(newPath, parameters, alreadyCloned, execute))
            {
                return false;
            }

            alreadyCloned.Add(targetModName + ':' + newAlias);
            if (execute)
            {
                string fileLocation = "file(" + newPath.Replace(mModule.Path.Replace(sourceModName, targetModName) + "/", "") + ")";
                ModuleFile file = new ModuleFile(targetModule, newAlias, fileLocation);
                file.TryLoad();
                if (file.FileData != null)
                {
                    targetModule.AddToManifest(newAlias, fileLocation);
                    targetModule.WriteManifestToFile();
                    return true;
                }
            }
            else
            {
                return true;
            }

            return false;
        }
Esempio n. 37
0
        private void AddModuleFiles(string fileType)
        {
            JToken fileTypes = mManifestJson[fileType];
            if (fileTypes != null)
            {
                Dictionary<string, ModuleFile> dictionary = new Dictionary<string, ModuleFile>();
                mModuleFiles[fileType] = dictionary;
                foreach (JToken item in fileTypes.Children())
                {
                    JProperty alias = item as JProperty;
                    string name = alias.Name.Trim();
                    string value = alias.Value.ToString().Trim();

                    ModuleFile moduleFile = new ModuleFile(this, name, value);
                    dictionary.Add(name, moduleFile);
                }
            }
        }