public async Task <IScriptType> GetScriptType(IList <string> modFiles)
        {
            CurrentScriptTypeRegistry = await ScriptTypeRegistry.DiscoverScriptTypes(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            IScriptType FoundScriptType = null;

            await Task.Run(() =>
            {
                foreach (IScriptType scriptType in CurrentScriptTypeRegistry.Types)
                {
                    bool HasFoundScriptType = false;
                    if (scriptType.FileNames != null)
                    {
                        foreach (string scriptFile in scriptType.FileNames)
                        {
                            // ??? Need to check for Fomod/Omod/Whatever before this part
                            string FileToFind = Path.Combine(FomodRoot, scriptFile);
                            string Match      = modFiles.Where(x => Path.GetFileName(x).Contains(scriptFile, StringComparison.OrdinalIgnoreCase) && Path.GetFileName(Path.GetDirectoryName(x)).Contains(FomodRoot, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                            if (!string.IsNullOrEmpty(Match))
                            {
                                HasFoundScriptType = true;
                                FoundScriptType    = scriptType;
                            }
                        }
                    }

                    if (HasFoundScriptType)
                    {
                        break;
                    }
                }
            });

            return(FoundScriptType);
        }
        /// <summary>
        /// Gets the specified <see cref="IScriptType"/>.
        /// </summary>
        /// <param name="scriptTypeId">The id of the <see cref="IScriptType"/> to retrieve.</param>
        /// <returns>The <see cref="IScriptType"/> whose id matches the given id. <c>null</c> is returned
        /// if no <see cref="IScriptType"/> with the given id is in the registry.</returns>
        public IScriptType GetType(string scriptTypeId)
        {
            IScriptType Type = null;

            ScriptTypes.TryGetValue(scriptTypeId, out Type);
            return(Type);
        }
示例#3
0
        /// <summary>
        /// Gets the specified <see cref="IScriptType"/>.
        /// </summary>
        /// <param name="p_strScriptTypeId">The id of the <see cref="IScriptType"/> to retrieve.</param>
        /// <returns>The <see cref="IScriptType"/> whose id matches the given id. <c>null</c> is returned
        /// if no <see cref="IScriptType"/> with the given id is in the registry.</returns>
        public IScriptType GetType(string p_strScriptTypeId)
        {
            IScriptType stpType = null;

            ScriptTypes.TryGetValue(p_strScriptTypeId, out stpType);
            return(stpType);
        }
示例#4
0
        public override IScriptType Invoke(params IScriptType[] arguments)
        {
            if (arguments.Length == 0)
            {
                PMWrapper.RaiseError("Kräver minst 1 värde till max().");
            }

            IScriptType max = null;

            foreach (IScriptType v in arguments)
            {
                if (max == null)
                {
                    max = v;
                    continue;
                }

                IScriptType result = v.CompareGreaterThan(max);

                if (result == null)
                {
                    PMWrapper.RaiseError($"Kan inte jämföra datatypen '{v.GetTypeName()}'.");
                }
                else if (result.IsTruthy())
                {
                    max = v;
                }
            }

            return(max);
        }
示例#5
0
        void ToStringAndCompressVariable(IScriptType variable, string s, int maxChars, out string text, out Color color)
        {
            switch (variable)
            {
            case IScriptBoolean _:
                color = boolText;
                text  = CompressString(s, maxChars);
                break;

            case IScriptInteger _:
            case IScriptDouble _:
                color = numberText;
                text  = CompressString(s, maxChars, isNumberValue: true);
                break;

            case IScriptString _:
                color = stringText;
                text  = CompressString(s, maxChars, isStringValue: true);
                break;

            case ScriptNull _:
                color = nullText;
                text  = variable.ToString();
                break;

            default:
                color = nullText;
                text  = IDEColorCoding.RunColorCode(CompressString(s, maxChars));
                break;
            }
        }
示例#6
0
        public void ResolveYield(IScriptType returnValue = null)
        {
            if (!isWalkerRunning)
            {
                return;
            }

            compiledCode?.ResolveYield(returnValue);
            sleepTimeLeft = 0;
        }
示例#7
0
 /// <summary>
 /// This provides interaction with the mod files.
 /// </summary>
 /// <param name="listModFiles">The list of files inside the mod archive.</param>
 /// <param name="stopPatterns">patterns matching files or directories that should be at the top of the directory structure.</param>
 /// <param name="installScriptPath">The path to the uncompressed install script file, if any.</param>
 /// <param name="tempFolderPath">Temporary path where install scripts can work.</param>
 /// <param name="scriptType">The script type, if any.</param>
 public Mod(List <string> listModFiles,
            List <string> stopPatterns,
            string installScriptPath, string tempFolderPath, IScriptType scriptType)
 {
     ModFiles     = listModFiles;
     StopPatterns = stopPatterns;
     GetScreenshotPath(listModFiles);
     InstallScriptPath = installScriptPath;
     TempPath          = tempFolderPath;
     InstallScriptType = scriptType;
 }
示例#8
0
        /// <summary>
        /// Loads the project from a file.
        /// </summary>
        /// <param name="p_strPath">The path to the file from which to load the project.</param>
        protected void Load(string p_strPath)
        {
            XmlDocument xmlProject = new XmlDocument();

            xmlProject.Load(p_strPath);

            XmlNode xndRoot = xmlProject.SelectSingleNode("modProject");

            XmlNode xndInfo = xndRoot.SelectSingleNode("info");

            this.LoadInfo(xndInfo);

            XmlNode xndScript = xndRoot.SelectSingleNode("InstallScript");

            if (xndScript != null)
            {
                IScriptType stpType = ScriptTypeRegistry.GetType(xndScript.Attributes["type"].Value);
                if (stpType == null)
                {
                    throw new Exception("Unrecognized script type: " + xndScript.Attributes["type"].Value);
                }
                InstallScript = stpType.LoadScript(xndScript.InnerXml);
            }

            XmlNode xndReadme = xndRoot.SelectSingleNode("ModReadme");

            if (xndReadme != null)
            {
                string       strFormat = xndReadme.Attributes["format"].Value;
                ReadmeFormat fmtFormat = ReadmeFormat.PlainText;
                if (Enum.GetNames(typeof(ReadmeFormat)).Contains(x => x.Equals(strFormat, StringComparison.InvariantCultureIgnoreCase)))
                {
                    fmtFormat = (ReadmeFormat)Enum.Parse(typeof(ReadmeFormat), strFormat);
                }
                ModReadme = new Readme(fmtFormat, xndReadme.InnerText);
            }

            XmlNode xndFiles = xndRoot.SelectSingleNode("ModFiles");

            if (xndFiles != null)
            {
                foreach (XmlNode xndFile in xndFiles.ChildNodes)
                {
                    bool booIsDirectory = false;
                    if (!bool.TryParse(xndFile.Attributes["IsDirectory"].Value, out booIsDirectory))
                    {
                        booIsDirectory = false;
                    }
                    ModFiles.Add(new VirtualFileSystemItem(xndFile.Attributes["Source"].Value, xndFile.Attributes["Path"].Value, booIsDirectory));
                }
            }
            FilePath = p_strPath;
            IsDirty  = false;
        }
示例#9
0
 public virtual IEnumerable <IScript> GetScripts(IScriptType scriptType)
 {
     if (scriptType == ScriptType.Initialize)
     {
         yield return(new CreateSchemaVersionJournal());
     }
     if (scriptType == ScriptType.Drop)
     {
         yield return(new DropSchema());
     }
 }
        /// <summary>
        /// Searches the given list of assemblies for script types, and registers any that are found.
        /// </summary>
        /// <param name="scriptTypeRegistry">The registry with which to register any found script types.</param>
        /// <param name="scriptAssemblies">The assemblies to search for script types.</param>
        private async static Task RegisterScriptTypes(IScriptTypeRegistry scriptTypeRegistry, IList <string> scriptAssemblies)
        {
            List <string> SupportedScriptDLLs = new List <string>()
            {
                "XmlScript.dll",
                "ModScript.dll",
                "CSharpScript.dll"
            };

            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            try
            {
                await Task.Run(() =>
                {
                    foreach (string assembly in scriptAssemblies)
                    {
                        foreach (string dll in SupportedScriptDLLs)
                        {
                            if (assembly.Contains(dll, StringComparison.OrdinalIgnoreCase))
                            {
                                Assembly CurrentAssembly = Assembly.LoadFrom(assembly);
                                Type[] Types             = CurrentAssembly.GetExportedTypes();
                                foreach (Type type in Types)
                                {
                                    if (typeof(IScriptType).IsAssignableFrom(type) && !type.IsAbstract)
                                    {
                                        Trace.TraceInformation("Initializing: {0}", type.FullName);
                                        Trace.Indent();

                                        IScriptType ScriptType      = null;
                                        ConstructorInfo Constructor = type.GetConstructor(new Type[] { });
                                        if (Constructor != null)
                                        {
                                            ScriptType = (IScriptType)Constructor.Invoke(null);
                                        }
                                        if (ScriptType != null)
                                        {
                                            scriptTypeRegistry.RegisterType(ScriptType);
                                        }

                                        Trace.Unindent();
                                    }
                                }
                            }
                        }
                    }
                });
            }
            finally
            {
                AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
            }
        }
示例#11
0
        public override IScriptType Invoke(params IScriptType[] arguments)
        {
            IScriptType v = arguments[0];

            if (v is IScriptString s)
            {
                return(Processor.Factory.Create(s.Value.Length));
            }

            PMWrapper.RaiseError($"Kan inte beräkna längden på värde av typen '{v.GetTypeName()}'.");
            return(Processor.Factory.Null);
        }
示例#12
0
 /// <summary>
 /// A simple constructor that initializes the script with the specified values.
 /// </summary>
 /// <param name="p_xstScripType">The script's type.</param>
 /// <param name="p_verVersion">The version of the script.</param>
 /// <param name="p_hdrHeader">The <see cref="HeaderInfo"/> of the script.</param>
 /// <param name="p_cndModPrerequisites">The mod prerequisites encoded in the script.</param>
 /// <param name="p_lstRequiredInstallFiles">The list of files that the script requires to be installed, regardless
 /// of other script options.</param>
 /// <param name="p_lstInstallSteps">The script's <see cref="InstallStep"/>s.</param>
 /// <param name="p_srtStepOrder">The order of the script's <see cref="InstallStep"/>s.</param>
 /// <param name="p_lstConditionallyInstalledFileSets">The list of file sets that the script wants installed if certain conditions
 /// are satified.</param>
 public XmlScript(XmlScriptType p_xstScripType, Version p_verVersion, HeaderInfo p_hdrHeader, ICondition p_cndModPrerequisites, IList <InstallableFile> p_lstRequiredInstallFiles, List <InstallStep> p_lstInstallSteps, SortOrder p_srtStepOrder, List <ConditionallyInstalledFileSet> p_lstConditionallyInstalledFileSets)
 {
     Type                            = p_xstScripType;
     Version                         = p_verVersion;
     HeaderInfo                      = p_hdrHeader;
     ModPrerequisites                = p_cndModPrerequisites;
     RequiredInstallFiles            = (p_lstRequiredInstallFiles == null) ? new ThreadSafeObservableList <InstallableFile>() : new ThreadSafeObservableList <InstallableFile>(p_lstRequiredInstallFiles);
     InstallSteps                    = (p_lstInstallSteps == null) ? new ThreadSafeObservableList <InstallStep>() : new ThreadSafeObservableList <InstallStep>(p_lstInstallSteps);
     InstallSteps.CollectionChanged += new NotifyCollectionChangedEventHandler(InstallSteps_CollectionChanged);
     InstallStepSortOrder            = p_srtStepOrder;
     ConditionallyInstalledFileSets  = (p_lstConditionallyInstalledFileSets == null) ? new ThreadSafeObservableList <ConditionallyInstalledFileSet>() : new ThreadSafeObservableList <ConditionallyInstalledFileSet>(p_lstConditionallyInstalledFileSets);
 }
        public async Task <IScriptType> GetScriptType(IList <string> modFiles, string extractedFilePath = null)
        {
            CurrentScriptTypeRegistry = await ScriptTypeRegistry.DiscoverScriptTypes(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            IScriptType FoundScriptType = null;

            string omodMatch = modFiles.Where(x => x.Equals("script") || x.Equals("script.txt")).FirstOrDefault();

            await Task.Run(() =>
            {
                foreach (IScriptType scriptType in CurrentScriptTypeRegistry.Types)
                {
                    bool HasFoundScriptType = false;
                    if (scriptType.FileNames != null)
                    {
                        foreach (string scriptFile in scriptType.FileNames)
                        {
                            string scriptDataString = "";
                            if (!string.IsNullOrEmpty(omodMatch))
                            {
                                byte[] scriptData = File.ReadAllBytes(Path.Combine(extractedFilePath, omodMatch));
                                scriptDataString  = System.Text.Encoding.Default.GetString(scriptData);
                            }

                            if (!string.IsNullOrEmpty(omodMatch) && scriptType.ValidateScript(scriptType.LoadScript(scriptDataString)))
                            {
                                HasFoundScriptType = true;
                                FoundScriptType    = scriptType;
                            }
                            else
                            {
                                string fomodMatch = modFiles.Where(x => scriptMatch(x, scriptFile)).FirstOrDefault();
                                if (!string.IsNullOrEmpty(fomodMatch))
                                {
                                    HasFoundScriptType = true;
                                    FoundScriptType    = scriptType;
                                }
                            }
                        }
                    }

                    if (HasFoundScriptType)
                    {
                        break;
                    }
                }
            });

            return(FoundScriptType);
        }
示例#14
0
        public override IScriptType Invoke(params IScriptType[] arguments)
        {
            IScriptType v = arguments[0];

            switch (v)
            {
            case IScriptInteger i:
                return(Processor.Factory.Create(i.Value));

            case IScriptDouble d:
                return(Processor.Factory.Create(Math.Round(d.Value)));

            default:
                PMWrapper.RaiseError($"Kan inte avrunda värde av typen '{v.GetTypeName()}'.");
                return(Processor.Factory.Null);
            }
        }
示例#15
0
        public override IScriptType Invoke(params IScriptType[] arguments)
        {
            IScriptType v = arguments[0];

            if (v is IScriptInteger i)
            {
                if (i.Value < 0)
                {
                    return(Processor.Factory.Create("-0b" + Convert.ToString(-i.Value, 2)));
                }

                return(Processor.Factory.Create("0b" + Convert.ToString(i.Value, 2)));
            }

            PMWrapper.RaiseError($"Kan inte konvertera typen '{v.GetTypeName()}' till binärt!");
            return(Processor.Factory.Null);
        }
        /// <summary>
        /// Searches the given list of assemblies for script types, and registers any that are found.
        /// </summary>
        /// <param name="p_stgScriptTypeRegistry">The registry with which to register any found script types.</param>
        /// <param name="p_enmAssemblies">The assemblies to search for script types.</param>
        private static void RegisterScriptTypes(IScriptTypeRegistry p_stgScriptTypeRegistry, IEnumerable <string> p_enmAssemblies, List <string> p_lstRemovedDLL)
        {
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
            try
            {
                foreach (string strAssembly in p_enmAssemblies)
                {
                    Trace.TraceInformation("Checking: {0}", Path.GetFileName(strAssembly));
                    Trace.Indent();

                    if (!p_lstRemovedDLL.Contains(Path.GetFileName(strAssembly)))
                    {
                        Assembly asmGameMode = Assembly.LoadFrom(strAssembly);
                        Type[]   tpeTypes    = asmGameMode.GetExportedTypes();
                        foreach (Type tpeType in tpeTypes)
                        {
                            if (typeof(IScriptType).IsAssignableFrom(tpeType) && !tpeType.IsAbstract)
                            {
                                Trace.TraceInformation("Initializing: {0}", tpeType.FullName);
                                Trace.Indent();

                                IScriptType     sctScriptType  = null;
                                ConstructorInfo cifConstructor = tpeType.GetConstructor(new Type[] { });
                                if (cifConstructor != null)
                                {
                                    sctScriptType = (IScriptType)cifConstructor.Invoke(null);
                                }
                                if (sctScriptType != null)
                                {
                                    p_stgScriptTypeRegistry.RegisterType(sctScriptType);
                                }

                                Trace.Unindent();
                            }
                        }
                    }
                    Trace.Unindent();
                }
            }
            finally
            {
                AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
            }
        }
 public async Task <List <SchemaVersionJournalEntry> > GetSchema(string schemaVersion = null, IScriptType type = null)
 {
     return((await Connection.QueryAsync <SchemaVersionJournalEntry>($@"
         SELECT * FROM (
             SELECT * FROM SchemaVersionJournal WHERE [Type] <> '{ScriptType.RunIfChanged.Name}' AND [Type] <> '{ScriptType.Deprecated.Name}'
             UNION ALL
             SELECT a.* FROM SchemaVersionJournal a 
             LEFT JOIN SchemaVersionJournal b on b.Name = a.Name AND b.Hash = a.Hash AND b.Id > a.Id AND b.Type = '{ScriptType.Deprecated.Name}'
             WHERE  b.Id IS NULL AND a.Id IN (
                 SELECT Max(Id) FROM SchemaVersionJournal WHERE [Type] = '{ScriptType.RunIfChanged.Name}' GROUP BY Name
             )
         ) _
         WHERE ([Version] = @version OR @version IS NULL) AND ([Type] = @type OR @type IS NULL)", new { type = type?.Name, version = schemaVersion })
             ).ToList());
 }
示例#18
0
        /// <summary>
        /// Performs the actual mod preparation work.
        /// </summary>
        /// <param name="p_objArgs">The task arguments.</param>
        /// <returns>Always <c>null</c>.</returns>
        protected override object DoWork(object[] p_objArgs)
        {
            string  strFileName   = (string)p_objArgs[0];
            Project prjModProject = (Project)p_objArgs[1];

            /*
             * 1) Create file dictionary
             * 2) Create info.xml
             * 3) Create screenshot
             * 4) Create readme
             * 5) Create XML Script
             * 6) Pack mod
             * 7) Clean up
             */

            string             strTmpDirectory = null;
            SevenZipCompressor szcCompressor   = null;

            try
            {
                ItemMessage         = "Finding Mod Files...";
                ItemProgressMaximum = prjModProject.ModFiles.Count;
                ItemProgress        = 0;
                Dictionary <string, string> dicFiles = new Dictionary <string, string>();
                foreach (VirtualFileSystemItem vfiItem in prjModProject.ModFiles)
                {
                    StepItemProgress();
                    if (vfiItem.IsDirectory)
                    {
                        continue;
                    }
                    dicFiles[vfiItem.Path] = vfiItem.Source;
                }

                StepOverallProgress();
                if (Status == TaskStatus.Cancelling)
                {
                    return(null);
                }

                strTmpDirectory = FileUtilities.CreateTempDirectory();

                ItemMessage         = "Generating Info File...";
                ItemProgressMaximum = 1;
                ItemProgress        = 0;
                string      strInfoFilePath = Path.Combine(strTmpDirectory, "info.xml");
                XmlDocument xmlInfo         = new XmlDocument();
                xmlInfo.AppendChild(prjModProject.SaveInfo(xmlInfo, false));
                xmlInfo.Save(strInfoFilePath);
                dicFiles[Path.Combine(NexusMod.MetaFolder, "info.xml")] = strInfoFilePath;

                StepOverallProgress();
                if (Status == TaskStatus.Cancelling)
                {
                    return(null);
                }

                if (prjModProject.Screenshot != null)
                {
                    ItemMessage         = "Generating Screenshot...";
                    ItemProgressMaximum = 1;
                    ItemProgress        = 0;

                    string strScreenshotPath = Path.Combine(strTmpDirectory, "screenshot.jpg");
                    strScreenshotPath = Path.ChangeExtension(strScreenshotPath, prjModProject.Screenshot.GetExtension());
                    File.WriteAllBytes(strScreenshotPath, prjModProject.Screenshot.Data);
                    dicFiles[Path.Combine(NexusMod.MetaFolder, Path.GetFileName(strScreenshotPath))] = strScreenshotPath;

                    StepOverallProgress();
                    if (Status == TaskStatus.Cancelling)
                    {
                        return(null);
                    }
                }

                if (prjModProject.ModReadme != null)
                {
                    ItemMessage         = "Generating Readme...";
                    ItemProgressMaximum = 1;
                    ItemProgress        = 0;

                    string strReadmePath = Path.Combine(strTmpDirectory, "readme.txt");
                    strReadmePath = Path.ChangeExtension(strReadmePath, prjModProject.ModReadme.Extension);
                    File.WriteAllText(strReadmePath, prjModProject.ModReadme.Text);
                    dicFiles[Path.Combine(NexusMod.MetaFolder, Path.GetFileName(strReadmePath))] = strReadmePath;

                    StepOverallProgress();
                    if (Status == TaskStatus.Cancelling)
                    {
                        return(null);
                    }
                }

                if (prjModProject.InstallScript != null)
                {
                    ItemMessage         = "Generating Install Script...";
                    ItemProgressMaximum = 1;
                    ItemProgress        = 0;

                    XDocument   xmlScript = new XDocument();
                    IScriptType stpType   = prjModProject.InstallScript.Type;
                    XElement    xelScript = XElement.Parse(stpType.SaveScript(prjModProject.InstallScript));
                    xmlScript.Add(xelScript);

                    string strScriptPath = Path.Combine(strTmpDirectory, stpType.FileNames[0]);
                    xmlScript.Save(strScriptPath);
                    dicFiles[Path.Combine(NexusMod.MetaFolder, stpType.FileNames[0])] = strScriptPath;

                    StepOverallProgress();
                    if (Status == TaskStatus.Cancelling)
                    {
                        return(null);
                    }
                }

                ItemMessage         = "Compressing Files...";
                ItemProgressMaximum = dicFiles.Count;
                ItemProgress        = 0;

                szcCompressor = new SevenZipCompressor();
                szcCompressor.CompressionLevel  = CompressionLevel.Fast;
                szcCompressor.ArchiveFormat     = OutArchiveFormat.SevenZip;
                szcCompressor.CompressionMethod = CompressionMethod.Default;
                switch (szcCompressor.ArchiveFormat)
                {
                case OutArchiveFormat.Zip:
                case OutArchiveFormat.GZip:
                case OutArchiveFormat.BZip2:
                    szcCompressor.CustomParameters.Add("mt", "on");
                    break;

                case OutArchiveFormat.SevenZip:
                case OutArchiveFormat.XZ:
                    szcCompressor.CustomParameters.Add("mt", "on");
                    szcCompressor.CustomParameters.Add("s", "off");
                    break;
                }
                szcCompressor.CompressionMode          = CompressionMode.Create;
                szcCompressor.FileCompressionStarted  += new EventHandler <FileNameEventArgs>(Compressor_FileCompressionStarted);
                szcCompressor.FileCompressionFinished += new EventHandler <EventArgs>(Compressor_FileCompressionFinished);

                szcCompressor.CompressFileDictionary(dicFiles, strFileName);
            }
            finally
            {
                if (!String.IsNullOrEmpty(strTmpDirectory))
                {
                    if (szcCompressor != null)
                    {
                        szcCompressor = null;
                        //this is bad form - really we should be disposing szcCompressor, but
                        // we can't as it doesn't implement IDisposable, so we have to rely
                        // on the garbage collector the force szcCompressor to release its
                        // resources (in this case, file locks)
                        System.GC.Collect();
                    }
                    //this try/catch is just in case the GC doesn't go as expected
                    // and szcCompressor didn't release its resources
                    try
                    {
                        FileUtil.ForceDelete(strTmpDirectory);
                    }
                    catch (IOException)
                    {
                    }
                }
            }
            return(null);
        }
示例#19
0
        /// <summary>
        /// This will simulate the mod installation and decide installation choices and files final paths.
        /// </summary>
        /// <param name="modArchiveFileList">The list of files inside the mod archive.</param>
        /// <param name="stopPatterns">patterns matching files or directories that should be at the top of the directory structure.</param>
        /// <param name="scriptPath">The path to the uncompressed install script file, if any.</param>
        /// <param name="progressDelegate">A delegate to provide progress feedback.</param>
        /// <param name="coreDelegate">A delegate for all the interactions with the js core.</param>
        public async override Task <Dictionary <string, object> > Install(List <string> modArchiveFileList,
                                                                          List <string> stopPatterns,
                                                                          string pluginPath,
                                                                          string scriptPath,
                                                                          ProgressDelegate progressDelegate,
                                                                          CoreDelegates coreDelegate)
        {
            IList <Instruction> Instructions  = new List <Instruction>();
            ModFormatManager    FormatManager = new ModFormatManager();
            string ScriptFilePath             = null;

            try
            {
                ScriptFilePath = new List <string>(await GetRequirements(modArchiveFileList, false)).FirstOrDefault();
            }
            catch (UnsupportedException)
            {
                // not an error, this can handle mods without an installer script (see BasicModInstall)
            }
            IScriptType ScriptType = await GetScriptType(modArchiveFileList);

            Mod modToInstall = new Mod(modArchiveFileList, stopPatterns, ScriptFilePath, scriptPath, ScriptType);
            await modToInstall.Initialize();

            progressDelegate(50);

            if (modToInstall.HasInstallScript)
            {
                Instructions = await ScriptedModInstall(modToInstall, progressDelegate, coreDelegate);

                if (Instructions == null)
                {
                    Instructions = new List <Instruction>();
                    Instructions.Add(Instruction.InstallError("Installer failed (it should have reported an error message)"));
                }
                else
                {
                    // f***ing ugly hack, but this is in NMM so...
                    if (pluginPath != null)
                    {
                        string pattern = pluginPath + Path.DirectorySeparatorChar;
                        Instructions = Instructions.Select(instruction =>
                        {
                            Instruction output = instruction;
                            if ((output.type == "copy") && output.destination.StartsWith(pattern, System.StringComparison.InvariantCultureIgnoreCase))
                            {
                                output.destination = output.destination.Substring(pattern.Length);
                            }
                            return(output);
                        }).ToList();
                    }
                }
            }
            else
            {
                Instructions = await BasicModInstall(modArchiveFileList, stopPatterns, progressDelegate, coreDelegate);
            }

            progressDelegate(100);

            return(new Dictionary <string, object>
            {
                { "message", "Installation successful" },
                { "instructions", Instructions }
            });
        }
示例#20
0
		/// <summary>
		/// Initializes an OMod in packed format.
		/// </summary>
		/// <param name="p_stgScriptTypeRegistry">The registry of supported script types.</param>
		private void InitializePackedOmod(IScriptTypeRegistry p_stgScriptTypeRegistry)
		{
			using (SevenZipExtractor szeOmod = new SevenZipExtractor(m_strFilePath))
			{
				ExtractConfig(szeOmod);
				ExtractPluginList(szeOmod);
				ExtractDataFileList(szeOmod);

				if (szeOmod.ArchiveFileNames.Contains("plugins.crc"))
					m_intReadOnlyInitFileBlockExtractionStages++;
				if (szeOmod.ArchiveFileNames.Contains("data.crc"))
					m_intReadOnlyInitFileBlockExtractionStages++;

				//check for script
				m_booHasInstallScript = false;
				foreach (IScriptType stpScript in p_stgScriptTypeRegistry.Types)
				{
					foreach (string strScriptName in stpScript.FileNames)
					{
						if (szeOmod.ArchiveFileNames.Contains(strScriptName))
						{
							using (MemoryStream stmScript = new MemoryStream())
							{
								szeOmod.ExtractFile(strScriptName, stmScript);
								string strCode = System.Text.Encoding.Default.GetString(stmScript.ToArray());
								if (stpScript.ValidateScript(stpScript.LoadScript(strCode)))
								{
									m_booHasInstallScript = true;
									m_stpInstallScriptType = stpScript;
									break;
								}
							}
						}
					}
					if (m_booHasInstallScript)
						break;
				}

				//check for readme
				m_booHasReadme = szeOmod.ArchiveFileNames.Contains("readme");

				//check for screenshot
				m_booHasScreenshot = szeOmod.ArchiveFileNames.Contains("image");
			}
		}
示例#21
0
		/// <summary>
		/// Initializes an OMod in OMod-ready archive format.
		/// </summary>
		/// <param name="p_booUseCache">Whether to use the mod cache.</param>
		/// <param name="p_mcmModCacheManager">The manager for the current game mode's mod cache.</param>
		/// <param name="p_stgScriptTypeRegistry">The registry of supported script types.</param>
		private void InitializeUnpackedOmod(bool p_booUseCache, IModCacheManager p_mcmModCacheManager, IScriptTypeRegistry p_stgScriptTypeRegistry)
		{
			if (p_booUseCache)
			{
				m_arcCacheFile = p_mcmModCacheManager.GetCacheFile(this);
				//check to make sure the cache isn't bad
				if ((m_arcCacheFile != null) && (!m_arcCacheFile.ContainsFile(GetRealPath(Path.Combine(CONVERSION_FOLDER, "config"))) || !ValidateConfig(GetSpecialFile("config"))))
				{
					//bad cache - clear it
					m_arcCacheFile.Dispose();
					m_arcCacheFile = null;
				}
			}

			//check for script
			m_booHasInstallScript = false;
			foreach (IScriptType stpScript in p_stgScriptTypeRegistry.Types)
			{
				foreach (string strScriptName in stpScript.FileNames)
				{
					if (ContainsFile(Path.Combine(CONVERSION_FOLDER, strScriptName)))
					{
						StreamReader sreScript = null;
						string strCode = String.Empty;

						if (File.Exists(Path.Combine(CONVERSION_FOLDER, strScriptName)))
						{
							sreScript = new StreamReader(Path.Combine(CONVERSION_FOLDER, strScriptName));
							strCode = sreScript.ReadToEnd();
							sreScript.Close();
						}
						else
							strCode = TextUtil.ByteToString(GetFile(Path.Combine(CONVERSION_FOLDER, strScriptName))).Trim('\0');

						if (!String.IsNullOrEmpty(strCode))
						{
							if (stpScript.ValidateScript(stpScript.LoadScript(strCode)))
							{
								m_booHasInstallScript = true;
								m_stpInstallScriptType = stpScript;
								break;
							}
						}
					}
				}
				if (m_booHasInstallScript)
					break;
			}

			//check for readme
			m_booHasReadme = ContainsFile(Path.Combine(CONVERSION_FOLDER, "readme"));

			//check for screenshot
			m_booHasScreenshot = ContainsFile(Path.Combine(CONVERSION_FOLDER, "screenshot"));

			if (p_booUseCache && (m_arcCacheFile == null))
			{
				string strTmpInfo = p_mcmModCacheManager.FileUtility.CreateTempDirectory();
				try
				{
					FileUtil.WriteAllBytes(Path.Combine(strTmpInfo, GetRealPath(Path.Combine(CONVERSION_FOLDER, "config"))), GetSpecialFile("config"));

					if (m_booHasReadme)
						FileUtil.WriteAllBytes(Path.Combine(strTmpInfo, GetRealPath(Path.Combine(CONVERSION_FOLDER, "readme"))), GetSpecialFile("readme"));

					if (m_booHasScreenshot)
						FileUtil.WriteAllBytes(Path.Combine(strTmpInfo, GetRealPath(Path.Combine(CONVERSION_FOLDER, ScreenshotPath))), GetSpecialFile(ScreenshotPath));

					m_arcCacheFile = p_mcmModCacheManager.CreateCacheFile(this, strTmpInfo);
				}
				finally
				{
					FileUtil.ForceDelete(strTmpInfo);
				}
			}

			LoadInfo(GetSpecialFile("config"));
		}
示例#22
0
 public EmbeddedScript(ResourceFile resourceFile, IScriptType type)
 {
     _resourceFile = resourceFile;
     _type         = type;
 }
		/// <summary>
		/// Registers the given <see cref="IScriptType"/>.
		/// </summary>
		/// <param name="p_stpType">A <see cref="IScriptType"/> to register.</param>
		public void RegisterType(IScriptType p_stpType)
		{
			ScriptTypes[p_stpType.TypeId] = p_stpType;
		}
示例#24
0
 /// <summary>
 /// Registers the given <see cref="IScriptType"/>.
 /// </summary>
 /// <param name="p_stpType">A <see cref="IScriptType"/> to register.</param>
 public void RegisterType(IScriptType p_stpType)
 {
     ScriptTypes[p_stpType.TypeId] = p_stpType;
 }
示例#25
0
		/// <summary>
		/// A simple constructor that initializes the FOMod from the specified file.
		/// </summary>
		/// <param name="p_strFilePath">The mod file from which to create the FOMod.</param>
		/// <param name="p_mftModFormat">The format of the mod.</param>
		/// <param name="p_strStopFolders">A list of folders names that indicate the root of the mod file structure.</param>
		/// <param name="p_strPluginsDirectoryName">The name of the folder that contains plugins.</param>
		/// <param name="p_mcmModCacheManager">The manager for the current game mode's mod cache.</param>
		/// <param name="p_stgScriptTypeRegistry">The registry of supported script types.</param>
		public FOMod(string p_strFilePath, FOModFormat p_mftModFormat, IEnumerable<string> p_enmStopFolders, string p_strPluginsDirectoryName, IEnumerable<string> p_enmPluginExtensions, IModCacheManager p_mcmModCacheManager, IScriptTypeRegistry p_stgScriptTypeRegistry, bool p_booUsePlugins)
		{
			StopFolders = new List<string>(p_enmStopFolders);
			if (!StopFolders.Contains("fomod", StringComparer.OrdinalIgnoreCase))
				StopFolders.Add("fomod");
			PluginsDirectoryName = p_strPluginsDirectoryName;
			PluginExtensions = new List<string>(p_enmPluginExtensions);

			Format = p_mftModFormat;
			ScriptTypeRegistry = p_stgScriptTypeRegistry;
			bool p_booUseCache = true;
			m_booUsesPlugins = p_booUsePlugins;
			bool booCheckNested = true;
			bool booCheckPrefix = true;
			bool booCheckScript = true;
			bool booUpdateCacheInfo = false;
			bool booDirtyCache = false;
			string strCheckPrefix = null;
			string strCheckScriptPath = null;
			string strCheckScriptType = null;

			m_strFilePath = p_strFilePath;
			m_arcFile = new Archive(p_strFilePath);

			#region Check for cacheInfo.txt file
			m_arcCacheFile = p_mcmModCacheManager.GetCacheFile(m_strFilePath);
			if (m_arcCacheFile != null)
			{
				if (m_arcCacheFile.ContainsFile("cacheInfo.txt"))
				{
					byte[] bCacheInfo = m_arcCacheFile.GetFileContents("cacheInfo.txt");
					string sCacheInfo = Encoding.UTF8.GetString(bCacheInfo, 0, bCacheInfo.Length);
					string[] strPref = sCacheInfo.Split(new string[] { "@@" }, StringSplitOptions.RemoveEmptyEntries);
					if (strPref.Length > 0)
					{
						booCheckNested = Convert.ToBoolean(strPref[0]);

						if (strPref.Length > 1)
						{
							strCheckPrefix = strPref[1];
							foreach (string Folder in IgnoreFolders)
							{
								if (strCheckPrefix.IndexOf(Folder, StringComparison.InvariantCultureIgnoreCase) >= 0)
								{
									booCheckNested = true;
									strCheckPrefix = String.Empty;
									booDirtyCache = true;
									break;
								}
							}
							
							if (!booDirtyCache)
							{

								if (strCheckPrefix.Equals("-"))
									strCheckPrefix = String.Empty;
								booCheckPrefix = false;

								if (strPref.Length > 2)
								{
									strCheckScriptPath = strPref[2];
									if (strCheckScriptPath.Equals("-"))
										strCheckScriptPath = String.Empty;
									strCheckScriptType = strPref[3];
									if (strCheckScriptType.Equals("-"))
										strCheckScriptType = String.Empty;
									booCheckScript = false;
								}
							}
						}
					}
				}
			}

			#endregion

			if (booCheckNested)
			{
				#region Temporary fix for nested .dazip files
				string[] strNested = m_arcFile.GetFiles("", "*.dazip", true);
				if (strNested.Length == 1)
				{
					string strFilePath = Path.Combine(Path.Combine(Path.GetTempPath(), "NMM"), strNested[0]);
					FileUtil.WriteAllBytes(strFilePath, GetFile(strNested[0]));
					if (File.Exists(strFilePath))
					{
						m_arcFile = new Archive(strFilePath);
						m_strNestedFilePath = strFilePath;
					}
				}
				#endregion
			}

			m_arcFile.ReadOnlyInitProgressUpdated += new CancelProgressEventHandler(ArchiveFile_ReadOnlyInitProgressUpdated);

			if (booCheckPrefix)
			{
				FindPathPrefix();
				booUpdateCacheInfo = true;
			}
			else
			{
				m_strPrefixPath = String.IsNullOrEmpty(strCheckPrefix) ? String.Empty : strCheckPrefix;
			}

			//check for script
			if (booCheckScript)
			{
				foreach (IScriptType stpScript in p_stgScriptTypeRegistry.Types)
				{
					foreach (string strScriptName in stpScript.FileNames)
					{
						string strScriptPath = Path.Combine("fomod", strScriptName);
						if (ContainsFile(strScriptPath))
						{
							m_strInstallScriptPath = strScriptPath;
							m_stpInstallScriptType = stpScript;
							break;
						}
					}
					if (!String.IsNullOrEmpty(m_strInstallScriptPath))
						break;
				}

				booUpdateCacheInfo = true;
			}
			else
			{
				m_strInstallScriptPath = strCheckScriptPath;
				m_stpInstallScriptType = String.IsNullOrEmpty(strCheckScriptType) ? null : p_stgScriptTypeRegistry.Types.FirstOrDefault(x => x.TypeName.Equals(strCheckScriptType));
			}

			if (p_booUseCache)
			{
				m_arcCacheFile = p_mcmModCacheManager.GetCacheFile(m_strFilePath);
				//check to make sure the cache isn't bad
				if ((m_arcCacheFile != null) && !m_arcCacheFile.ContainsFile(GetRealPath("fomod/info.xml")))
				{
					//bad cache - clear it
					m_arcCacheFile.Dispose();
					m_arcCacheFile = null;
				}
			}
			m_arcFile.FilesChanged += new EventHandler(Archive_FilesChanged);

			//check for readme
			string strBaseName = Path.GetFileNameWithoutExtension(p_strFilePath);
			for (int i = 0; i < Readme.ValidExtensions.Length; i++)
				if (ContainsFile("readme - " + strBaseName + Readme.ValidExtensions[i]))
				{
					m_strReadmePath = "Readme - " + strBaseName + Readme.ValidExtensions[i];
					break;
				}
			if (String.IsNullOrEmpty(m_strReadmePath))
				for (int i = 0; i < Readme.ValidExtensions.Length; i++)
					if (ContainsFile("docs/readme - " + strBaseName + Readme.ValidExtensions[i]))
					{
						m_strReadmePath = "docs/Readme - " + strBaseName + Readme.ValidExtensions[i];
						break;
					}

			//check for screenshot
			string[] strScreenshots;
			if (p_booUseCache && (m_arcCacheFile != null))
				strScreenshots = m_arcCacheFile.GetFiles(GetRealPath("fomod"), "screenshot*", false);
			else
				strScreenshots = m_arcFile.GetFiles(GetRealPath("fomod"), "screenshot*", false);
			//TODO make sure the file is a valid image
			if (strScreenshots.Length > 0)
				m_strScreenshotPath = strScreenshots[0];

			if (p_booUseCache && (m_arcCacheFile == null))
			{
				string strTmpInfo = p_mcmModCacheManager.FileUtility.CreateTempDirectory();
				try
				{
					Directory.CreateDirectory(Path.Combine(strTmpInfo, GetRealPath("fomod")));

					if (ContainsFile("fomod/info.xml"))
						FileUtil.WriteAllBytes(Path.Combine(strTmpInfo, GetRealPath("fomod/info.xml")), GetFile("fomod/info.xml"));
					else
						FileUtil.WriteAllText(Path.Combine(strTmpInfo, GetRealPath("fomod/info.xml")), "<fomod/>");

					if (!String.IsNullOrEmpty(m_strReadmePath))
						FileUtil.WriteAllBytes(Path.Combine(strTmpInfo, GetRealPath(m_strReadmePath)), GetFile(m_strReadmePath));

					if (!String.IsNullOrEmpty(m_strScreenshotPath))
						FileUtil.WriteAllBytes(Path.Combine(strTmpInfo, GetRealPath(m_strScreenshotPath)), GetFile(m_strScreenshotPath));

					m_arcCacheFile = p_mcmModCacheManager.CreateCacheFile(this, strTmpInfo);
				}
				finally
				{
					FileUtil.ForceDelete(strTmpInfo);
				}
			}

			if (booUpdateCacheInfo || (!m_arcCacheFile.ContainsFile("cacheInfo.txt")))
			{

				Byte[] bteText = new UTF8Encoding(true).GetBytes(String.Format("{0}@@{1}@@{2}@@{3}",
					(!String.IsNullOrEmpty(m_strNestedFilePath)).ToString(),
					String.IsNullOrEmpty(m_strPrefixPath) ? "-" : m_strPrefixPath,
					String.IsNullOrEmpty(m_strInstallScriptPath) ? "-" : m_strInstallScriptPath,
					(m_stpInstallScriptType == null) ? "-" : m_stpInstallScriptType.TypeName));

				if (bteText != null)
					m_arcCacheFile.ReplaceFile("cacheInfo.txt", bteText);
			}

			ModName = Path.GetFileNameWithoutExtension(m_strFilePath);
			LoadInfo();
		}
示例#26
0
 public ScriptToolItem(IScriptType scriptType, ILocalPlayer player)
 {
     this.scriptType = scriptType;
     this.player     = player;
 }
 public virtual IEnumerable <IScript> GetScripts(IScriptType type)
 {
     return(EmbeddedResourceReader.GetResourcesFrom(_scriptsAssembly, x => x.StartsWith($"{_namespacePrefix}.{_scriptsRootFolder}.{type.Name}"))
            .Select(x => new EmbeddedScript(x, type)).OrderBy(x => x.Name).ToList());
 }
 /// <summary>
 /// Registers the given <see cref="IScriptType"/>.
 /// </summary>
 /// <param name="scriptType">A <see cref="IScriptType"/> to register.</param>
 public void RegisterType(IScriptType scriptType)
 {
     ScriptTypes[scriptType.TypeId] = scriptType;
 }