Ejemplo n.º 1
0
        /// <summary>
        /// Finds and compiles Emmet source file.
        /// </summary>
        /// <exception cref="FileNotFoundException">
        /// Indicates that Emmet script was not found.
        /// </exception>
        public void CompileCore()
        {
            string extensionFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string emmetScript     = Path.Combine(extensionFolder, @"emmet-min.js");

            if (!File.Exists(emmetScript))
            {
                throw new FileNotFoundException("Emmet script not found.", emmetScript);
            }

            ObjectHandle window = _engine.CreateObject();

            _engine.DynamicGlobalObject.window = window;

            Handle script = _engine.LoadScript(emmetScript, "Emmet");

            if (script.IsError)
            {
                this.TraceError(script.AsString);
                throw new Exception <EmmetEngineExceptionArgs>(
                          new EmmetEngineExceptionArgs("Failed to compile Emmet", script));
            }
            else
            {
                this.Trace("Emmet core compiled successfully.");
            }
        }
        protected override async Task OnLoadAsync()
        {
            var scriptsDir = Path.Combine(m_Runtime.WorkingDirectory, "scripts");
            var nativeDir  = Path.Combine(m_Runtime.WorkingDirectory, "native");

            if (!s_Initialized)
            {
                if (!Directory.Exists(nativeDir))
                {
                    Directory.CreateDirectory(nativeDir);
                }

                var latestPackageId = await m_NuGetPackageManager.GetLatestPackageIdentityAsync("V8.NET");

                var nupkgFile     = m_NuGetPackageManager.GetNugetPackageFile(latestPackageId);
                var packageReader = new PackageArchiveReader(nupkgFile);
                foreach (var file in packageReader.GetFiles("contentFiles"))
                {
                    if (!file.Contains("netstandard2.0"))
                    {
                        continue;
                    }

                    var fileName = Path.GetFileName(file);
                    var entry    = packageReader.GetEntry(file);
                    using var stream = entry.Open();
                    var ms = new FileStream(Path.Combine(nativeDir, fileName), FileMode.Create);
                    await stream.CopyToAsync(ms);

                    ms.Close();
                    stream.Close();
                }

                Loader.AlternateRootSubPath = nativeDir;
                s_Initialized = true;
            }

            if (!Directory.Exists(scriptsDir))
            {
                Directory.CreateDirectory(scriptsDir);
            }
            else
            {
                foreach (var directory in Directory.GetDirectories(scriptsDir))
                {
                    m_Logger.LogInformation($"[loading] Script: {directory}");

                    var filePath = Path.Combine(directory, "startup.js");
                    if (!File.Exists(filePath))
                    {
                        continue;
                    }

                    var scriptId = new DirectoryInfo(directory).Name;

                    m_Engine = new V8Engine(true);
                    var globalContext = m_Engine.GetContext();
                    var v8Context     = m_Engine.CreateContext();

                    var scriptLifeTime = m_LifetimeScope.BeginLifetimeScope(builder =>
                    {
                        builder.Register(ctx => m_Engine)
                        .As <V8Engine>()
                        .SingleInstance()
                        .OwnedByLifetimeScope();

                        builder.Register(ctx => v8Context)
                        .As <Context>()
                        .SingleInstance()
                        .OwnedByLifetimeScope();
                    });

                    try
                    {
                        var serviceProvider = scriptLifeTime.Resolve <IServiceProvider>();
                        m_Engine.SetContext(v8Context);
                        m_Engine.GlobalObject.SetProperty("logger", ActivatorUtilities.CreateInstance <ScriptLogger>(serviceProvider, scriptId), memberSecurity: ScriptMemberSecurity.Locked);
                        m_Engine.GlobalObject.SetProperty("openmod", ActivatorUtilities.CreateInstance <OpenModFunctions>(serviceProvider), memberSecurity: ScriptMemberSecurity.Locked);
                        var script = m_Engine.LoadScript(filePath, throwExceptionOnError: true);
                        m_Engine.Execute(script, throwExceptionOnError: true, trackReturn: false);
                        m_Engine.SetContext(globalContext);
                        GC.KeepAlive(script);
                    }
                    catch (Exception ex)
                    {
                        m_Logger.LogError(ex.GetBaseException(), $"Script error in script \"{scriptId}\"");
                    }
                }
            }
        }
Ejemplo n.º 3
0
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            returnValue = CefV8Value.CreateNull();
            exception   = null;

            try
            {
                var context = CefV8Context.GetCurrentContext();
                var browser = context.GetBrowser();
                var frame   = browser.GetMainFrame();

                if (name == "compile" || name == "loadScript" || name == "loadScriptCompiled")
                {
                    if (arguments.Length >= 3)
                    {
                        var script                = arguments[0].GetStringValue();
                        var sourceName            = arguments[1].GetStringValue();
                        var throwExceptionOnError = arguments[2].GetBoolValue();
                        var callback              = (arguments.Length == 4 ? arguments[3] : null);

                        if (!string.IsNullOrEmpty(script) && !string.IsNullOrEmpty(sourceName))
                        {
                            if (callback != null && callback.IsFunction)
                            {
                                var runner = CefTaskRunner.GetForCurrentThread();
                                new Task(() =>
                                {
                                    context.Enter();
                                    if (name == "compile")
                                    {
                                        engine.Compile(script, sourceName, throwExceptionOnError);
                                    }
                                    else if (name == "loadScript")
                                    {
                                        engine.LoadScript(script, sourceName, throwExceptionOnError);
                                    }
                                    else if (name == "loadScriptCompiled")
                                    {
                                        engine.LoadScriptCompiled(script, sourceName, throwExceptionOnError);
                                    }
                                    runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(new StatusHelper("OK", name))));
                                    context.Exit();
                                }).Start();
                            }
                            else
                            {
                                if (name == "compile")
                                {
                                    engine.Compile(script, sourceName, throwExceptionOnError);
                                }
                                else if (name == "loadScript")
                                {
                                    engine.LoadScript(script, sourceName, throwExceptionOnError);
                                }
                                else if (name == "loadScriptCompiled")
                                {
                                    engine.LoadScriptCompiled(script, sourceName, throwExceptionOnError);
                                }
                                returnValue = CefV8Value.CreateString(JsonMapper.ToJson(new StatusHelper("OK", name)));
                            }
                        }
                        else
                        {
                            returnValue = DontMeetRequirements(context, callback);
                        }
                    }
                    else
                    {
                        returnValue = DontMeetRequirements(context, null);
                    }
                }
                else if (name == "consoleExecute" || name == "execute" || name == "verboseConsoleExecute")
                {
                    if (arguments.Length >= 4)
                    {
                        var script                = arguments[0].GetStringValue();
                        var sourceName            = arguments[1].GetStringValue();
                        var throwExceptionOnError = arguments[2].GetBoolValue();
                        var timeOut               = arguments[3].GetIntValue();
                        var callback              = (arguments.Length == 5 ? arguments[4] : null);

                        if (!string.IsNullOrEmpty(script) && !string.IsNullOrEmpty(sourceName))
                        {
                            if (callback != null && callback.IsFunction)
                            {
                                var runner = CefTaskRunner.GetForCurrentThread();
                                new Task(() =>
                                {
                                    context.Enter();
                                    if (name == "consoleExecute")
                                    {
                                        engine.ConsoleExecute(script, sourceName, throwExceptionOnError, timeOut);
                                    }
                                    else if (name == "execute")
                                    {
                                        engine.Execute(script, sourceName, throwExceptionOnError, timeOut);
                                    }
                                    else if (name == "verboseConsoleExecute")
                                    {
                                        engine.VerboseConsoleExecute(script, sourceName, throwExceptionOnError, timeOut);
                                    }
                                    runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(new StatusHelper("OK", name))));
                                    context.Exit();
                                }).Start();
                            }
                            else
                            {
                                if (name == "consoleExecute")
                                {
                                    engine.ConsoleExecute(script, sourceName, throwExceptionOnError, timeOut);
                                }
                                else if (name == "execute")
                                {
                                    engine.Execute(script, sourceName, throwExceptionOnError, timeOut);
                                }
                                else if (name == "verboseConsoleExecute")
                                {
                                    engine.VerboseConsoleExecute(script, sourceName, throwExceptionOnError, timeOut);
                                }
                                returnValue = CefV8Value.CreateString(JsonMapper.ToJson(new StatusHelper("OK", name)));
                            }
                        }
                        else
                        {
                            returnValue = DontMeetRequirements(context, callback);
                        }
                    }
                    else
                    {
                        returnValue = DontMeetRequirements(context, null);
                    }
                }
                else if (name == "terminateExecution")
                {
                    if (arguments.Length >= 0)
                    {
                        var callback = (arguments.Length == 1 ? arguments[0] : null);

                        if (callback != null && callback.IsFunction)
                        {
                            var runner = CefTaskRunner.GetForCurrentThread();
                            new Task(() =>
                            {
                                context.Enter();
                                engine.TerminateExecution();
                                runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(new StatusHelper("OK", "TerminateExecution"))));
                                context.Exit();
                            }).Start();
                        }
                        else
                        {
                            engine.TerminateExecution();
                            returnValue = CefV8Value.CreateString(JsonMapper.ToJson(new StatusHelper("OK", "TerminateExecution")));
                        }
                    }
                    else
                    {
                        returnValue = DontMeetRequirements(context, null);
                    };
                }
                else if (name == "runStartupFile")
                {
                    if (arguments.Length >= 0)
                    {
                        var callback = (arguments.Length == 1 ? arguments[0] : null);

                        if (callback != null && callback.IsFunction)
                        {
                            var runner = CefTaskRunner.GetForCurrentThread();
                            new Task(() =>
                            {
                                context.Enter();

                                var message = "V8 Script Engine : Started";
                                Log.Trace(message, configuration.Verbose);
                                runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(new StatusHelper("OK", message))));

                                context.Exit();
                            }).Start();
                        }
                        else
                        {
                            var message = "V8 Script Engine : Started";
                            Log.Trace(message, configuration.Verbose);
                            returnValue = CefV8Value.CreateString(JsonMapper.ToJson(new StatusHelper("OK", message)));
                        }
                    }
                    else
                    {
                        returnValue = DontMeetRequirements(context, null);
                    };
                }
                return(true);
            }
            catch (Exception ex)
            {
                returnValue = CefV8Value.CreateNull();
                exception   = ex.Message;
                return(true);
            }
        }