예제 #1
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
              
                string script;
                if (reference == 0)
                {
                    script = string.Format("delete {0}", this.ns);
                }
                else
                {
                    var origin = this.origin;
                    if (origin != null)
                        script = string.Format("{0}.$releaseObject(${1})", origin.ns, reference);
                    else return;
                }
                var _ = _context.NKevaluateJavaScript(script);
                _context = null;
                _origin = null;
                _context = null;
                _origin = null;
                reference = 0;
                ns = null;

                disposedValue = true;
            }
        }
        protected virtual void unbind()
        {
            var context = this.context;

            if (_channels.ContainsKey(ns))
            {
                _channels.Remove(ns);
            }
            if (id == null)
            {
                return;
            }
            id = null;
            _instances.Clear();
            if (isFactory)
            {
                _principal.nativeObject.setNKScriptChannel(null);
            }
            _principal = null;
            context.NKremoveScriptMessageHandlerForName(id);
            _context   = null;
            _typeInfo  = null;
            _queue     = null;
            _instances = null;
            context    = null;
        }
        internal NKScriptValueNative(object value, NKScriptContext context) : base()
        {

            Type t = value.GetType();
            NKScriptChannelProtocol channel = t.getNKScriptChannel();
            if (channel == null)
            {
                channel = t.GetTypeInfo().BaseType.getNKScriptChannel();
                if (channel == null)
                    throw new MissingFieldException("Cannot find channel for NKScriptExport member " + t.Name);
            }

            string pluginNS = channel.ns;
            int id = channel.getNativeSeq();
            _instanceid = id;
            string ns = string.Format("{0}[{1}]", pluginNS, id);
            this._channel = channel;
          
            // super.init(ns: ns, context: channel, origin: nil)
            _context = context;

            this.ns = ns;
            if (origin != null)
                _origin = origin;
            else
                _origin = this;
            // end super init

            channel.addInstance(id, this);
            proxy = bindObject(value);
            syncCreationWithProperties();
        }
예제 #4
0
        public async static Task bootCore(NKScriptContext context, Dictionary<string, object> options)
        {
            // FINALLY LOAD BOOTSTRAP CODE AFTER ALL PLATFORM PLUGINS
            var appjs = await NKStorage.getResourceAsync(typeof(Main), "_nodekit_bootstrapper.js", "lib");
            var script = "function loadbootstrap(){\n" + appjs + "\n}\n" + "loadbootstrap();" + "\n";
            var scriptsource = new NKScriptSource(script, "io.nodekit.core/lib-core/_nodekit_bootstrapper.js", "io.nodekit.core.bootstrapper");
            await context.NKinjectScript(scriptsource);

        }
예제 #5
0
 internal NKScriptValue(string ns, NKScriptContext context, NKScriptValue origin)
 {
     this.ns = ns;
     _context = context;
     if (origin != null)
         _origin = origin;
     else
         _origin = this;
 }
예제 #6
0
        public async static Task bootCore(NKScriptContext context, Dictionary <string, object> options)
        {
            // FINALLY LOAD BOOTSTRAP CODE AFTER ALL PLATFORM PLUGINS
            var appjs = await NKStorage.getResourceAsync(typeof(Main), "_nodekit_bootstrapper.js", "lib");

            var script       = "function loadbootstrap(){\n" + appjs + "\n}\n" + "loadbootstrap();" + "\n";
            var scriptsource = new NKScriptSource(script, "io.nodekit.core/lib-core/_nodekit_bootstrapper.js", "io.nodekit.core.bootstrapper");
            await context.NKinjectScript(scriptsource);
        }
예제 #7
0
        public async static Task addElectro(NKScriptContext context, Dictionary <string, object> options)
        {
            var appjs = await NKStorage.getResourceAsync(typeof(Main), "_nke_main.js", "lib_electro");

            var script       = "function loadbootstrap(){\n" + appjs + "\n}\n" + "loadbootstrap();" + "\n";
            var scriptsource = new NKScriptSource(script, "io.nodekit.electro/lib-electro/_nke_main.js", "io.nodekit.electro.main");
            await context.NKinjectScript(scriptsource);

            bool multiProcess = NKOptions.itemOrDefault <bool>(options, "NKS.RemoteProcess", false);

            var optionsDefault = new Dictionary <string, object>
            {
                ["NKS.PluginBridge"] = NKScriptExportType.NKScriptExport
            };

            var optionsMulti = new Dictionary <string, object>
            {
                ["NKS.PluginBridge"]  = NKScriptExportType.NKScriptExport,
                ["NKS.RemoteProcess"] = true
            };

            var optionsMain = new Dictionary <string, object>
            {
                ["NKS.PluginBridge"]        = NKScriptExportType.NKScriptExport,
                ["NKS.MainThread"]          = true,
                ["NKS.MainThreadId"]        = (int)options["NKS.MainThreadId"],
                ["NKS.MainThreadScheduler"] = (TaskScheduler)options["NKS.MainThreadScheduler"]
            };

            await context.NKloadPlugin(typeof(NKE_App), null, optionsDefault);

            if (!multiProcess)
            {
                await NKE_BrowserWindow.attachToContext(context, optionsMain);
            }
            else
            {
                await NKE_BrowserWindow.attachToContext(context, optionsMulti);
            }

            if (!multiProcess)
            {
                await NKE_WebContents.attachToContext(context, optionsMain);
            }
            else
            {
                await NKE_WebContents.attachToContext(context, optionsMulti);
            }

            await NKE_Dialog.attachToContext(context, optionsMain);

            await NKE_IpcMain.attachToContext(context, optionsDefault);

            // NKE_Menu.attachTo(context);
            // NKE_Protocol.attachTo(context);
        }
예제 #8
0
 internal Task initializeForContext(NKScriptContext context)
 {
     if (_initializeForContext != null)
     {
         return((Task)_initializeForContext.Invoke(instance, new[] { context }));
     }
     else
     {
         return(Task.FromResult <object>(null));
     }
 }
예제 #9
0
        private static Task initializeForContext(NKScriptContext context)
        {
            var jsValue = typeof(NKE_IpcMain).getNKScriptValue();
            var events  = NKEventEmitter.global;

            globalEvents.on <NKEvent>("NKE.IPCtoMain", (e, item) =>
            {
                jsValue.invokeMethod("emit", new object[] { "NKE.IPCtoMain", item.sender, item.channel, item.replyId, item.arg });
            });

            return(Task.FromResult <object>(null));
        }
예제 #10
0
        private static Task initializeForContext(NKScriptContext context)
        {
            var jsValue = typeof(NKE_IpcMain).getNKScriptValue();
            var events = NKEventEmitter.global;

            globalEvents.on<NKEvent>("NKE.IPCtoMain", (e, item) =>
            {
                jsValue.invokeMethod("emit", new object[] { "NKE.IPCtoMain", item.sender, item.channel, item.replyId, item.arg });
            });

            return Task.FromResult<object>(null);
        }
예제 #11
0
        private static Task initializeForContext(NKScriptContext context)
        {
            windowCount = 0;
            var jsValue = typeof(NKE_App).getNKScriptValue();
            var events  = NKEventEmitter.global;

            // Event: 'ready'
            events.once <string>("NK.AppReady", (e, data) =>
            {
                jsValue.invokeMethod("emit", new[] { "ready" });
            });

            events.once <string>("NK.AppDidFinishLaunching", (e, data) =>
            {
                jsValue.invokeMethod("emit", new[] { "will-finish-launching" });
            });

            events.once <string>("NK.AppWillTerminate", (e, data) =>
            {
                jsValue.invokeMethod("emit", new[] { "will-quit" });
                jsValue.invokeMethod("emit", new[] { "quit" });
            });

            events.on <string>("NKS.ProcessAdded", (e, data) => windowCount++);
            events.on <string>("NKE.WindowAdded", (e, data) => windowCount++);

            events.on <string>("NKS.ProcessRemoved", (e, data) =>
            {
                windowCount--;
                if (windowCount == 0)
                {
                    events.emit <string>("NKE.WindowAllClosed", "");
                }
            });

            events.on <string>("NKE.WindowRemoved", (e, data) =>
            {
                windowCount--;
                if (windowCount == 0)
                {
                    events.emit <string>("NKE.WindowAllClosed", "");
                }
            });

            events.once <string>("NKE.WindowAllClosed", (e, data) =>
            {
                //   exit(0);
                jsValue.invokeMethod("emit", new[] { "window-all-closed" });
            });

            return(Task.FromResult <object>(null));
        }
예제 #12
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                eject();
                source   = null;
                cleanup  = null;
                filename = null;
                _context = null;
                _context = null;

                disposedValue = true;
            }
        }
예제 #13
0
        public async static Task addElectro(NKScriptContext context, Dictionary<string, object> options)
        {
            var appjs = await NKStorage.getResourceAsync(typeof(Renderer), "_nke_renderer.js", "lib_electro");
            var script = "function loadbootstrap(){\n" + appjs + "\n}\n" + "loadbootstrap();" + "\n";
            var scriptsource = new NKScriptSource(script, "io.nodekit.electro/lib-electro/_nke_renderer.js", "io.nodekit.electro.renderer");
            await context.NKinjectScript(scriptsource);

            var optionsDefault = new Dictionary<string, object>
            {
                ["NKS.PluginBridge"] = NKScriptExportType.NKScriptExport
            };

            await NKE_IpcRenderer.attachToContext(context, optionsDefault);

        }
예제 #14
0
        public async static Task addElectro(NKScriptContext context, Dictionary <string, object> options)
        {
            var appjs = await NKStorage.getResourceAsync(typeof(Renderer), "_nke_renderer.js", "lib_electro");

            var script       = "function loadbootstrap(){\n" + appjs + "\n}\n" + "loadbootstrap();" + "\n";
            var scriptsource = new NKScriptSource(script, "io.nodekit.electro/lib-electro/_nke_renderer.js", "io.nodekit.electro.renderer");
            await context.NKinjectScript(scriptsource);

            var optionsDefault = new Dictionary <string, object>
            {
                ["NKS.PluginBridge"] = NKScriptExportType.NKScriptExport
            };

            await NKE_IpcRenderer.attachToContext(context, optionsDefault);
        }
예제 #15
0
        private static Task initializeForContext(NKScriptContext context)
        {
            windowCount = 0;
            var jsValue = typeof(NKE_App).getNKScriptValue();
            var events = NKEventEmitter.global;

            // Event: 'ready'
            events.once<string>("NK.AppReady", (e, data) =>
            {
                jsValue.invokeMethod("emit", new[] { "ready" });
            });

            events.once<string>("NK.AppDidFinishLaunching", (e, data) =>
            {
                jsValue.invokeMethod("emit", new[] { "will-finish-launching" });
            });

            events.once<string>("NK.AppWillTerminate", (e, data) =>
            {
                jsValue.invokeMethod("emit", new[] { "will-quit" });
                jsValue.invokeMethod("emit", new[] { "quit" });
            });

            events.on<string>("NKS.ProcessAdded", (e, data) => windowCount++);
            events.on<string>("NKE.WindowAdded", (e, data) => windowCount++);

            events.on<string>("NKS.ProcessRemoved", (e, data) =>
            {
                windowCount--;
                if (windowCount == 0)
                    events.emit<string>("NKE.WindowAllClosed", "");
            });

            events.on<string>("NKE.WindowRemoved", (e, data) =>
            {
                windowCount--;
                if (windowCount == 0)
                    events.emit<string>("NKE.WindowAllClosed", "");
            });

            events.once<string>("NKE.WindowAllClosed", (e, data) =>
            {
             //   exit(0);
                 jsValue.invokeMethod("emit", new[] { "window-all-closed" });
            });

            return Task.FromResult<object>(null);
          }
예제 #16
0
        public async static Task addCorePlatform(NKScriptContext context, Dictionary<string, object> options)
        {
            entryType = (System.Type)options["NKS.Entry"];


            // PROCESS SHOULD BE FIRST CORE PLATFORM PLUGIN
            await NKC_Process.attachToContext(context, options);

            // LOAD REMAINING CORE PLATFORM PLUGINS
            await NKC_FileSystem.attachToContext(context, options);
      //      await NKC_Console.attachToContext(context, options);
            await NKC_Crypto.attachToContext(context, options);
            await NKC_SocketTCP.attachToContext(context, options);
            await NKC_SocketUDP.attachToContext(context, options);
            await NKC_Timer.attachToContext(context, options);
        }
예제 #17
0
        private async Task startNodeKitRenderer(Dictionary <string, object> options)
        {
            string[] args = (string[])options["NKS.Args"];

            NKEventEmitter.isMainProcess = false;

            options.set("NKS.MainThreadScheduler", TaskScheduler.FromCurrentSynchronizationContext());
            options.set("NKS.MainThreadId", Environment.CurrentManagedThreadId);
            options.set("NKS.RemoteProcess", true);

            proxy   = NKRemoting.NKRemotingProxy.registerAsClient(args[0]);
            context = await NKScripting.Engines.NKRemoting.NKSNKRemotingContext.createContext(proxy, options);

            // REMOTE SCRIPT ENGINE LOADED, ADD {NK} NODEKIT PROXY
            await NKElectro.Main.addElectroRemoteProxy(context, options);

            proxy.NKready();
        }
예제 #18
0
        private async Task startNodeKitRenderer(Dictionary<string, object> options)
        {
            string[] args = (string[])options["NKS.Args"];

            NKEventEmitter.isMainProcess = false;

            options.set("NKS.MainThreadScheduler", TaskScheduler.FromCurrentSynchronizationContext());
            options.set("NKS.MainThreadId", Environment.CurrentManagedThreadId);
            options.set("NKS.RemoteProcess", true);

            proxy = NKRemoting.NKRemotingProxy.registerAsClient(args[0]);
            context = await NKScripting.Engines.NKRemoting.NKSNKRemotingContext.createContext(proxy, options);

            // REMOTE SCRIPT ENGINE LOADED, ADD {NK} NODEKIT PROXY
            await NKElectro.Main.addElectroRemoteProxy(context, options);

            proxy.NKready();
        }
예제 #19
0
        //RENDERER
        private NKRemotingProxy(string[] args)
        {
            NKLogging.log("+Started Renderer in new Process");
            this.context           = null;
            this._localHandlers    = new Dictionary <string, NKScriptMessageHandler>();
            this.cancelTokenSource = new CancellationTokenSource();
            this.cancelToken       = cancelTokenSource.Token;

            var outHandle = args[2];
            var inHandle  = args[1];

            var syncPipeOut = new AnonymousPipeClientStream(PipeDirection.Out, outHandle);
            var syncPipeIn  = new AnonymousPipeClientStream(PipeDirection.In, inHandle);

            this.syncPipeOut = syncPipeOut;
            this.syncPipeIn  = syncPipeIn;

            syncPipeIn.ReadByte();

            var handshake = readObject(syncPipeIn);

            if (handshake.command != NKRemotingMessage.Command.NKRemotingHandshake)
            {
                Environment.Exit(911);
            }

            var pipeName = handshake.args[0];

            ns = handshake.args[1];
            id = handshake.args[2];
            NKScriptChannel.nativeFirstSequence = Int32.Parse(handshake.args[3]);

            handshake.args = new string[] { };
            writeObject(syncPipeOut, handshake);

            var asyncPipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough);

            asyncPipe.Connect();
            cancelToken.Register(requestSelfTeardown);

            this.asyncPipe = asyncPipe;

            Task.Factory.StartNew((s) => _processClientMessages(), null, cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }
예제 #20
0
        // RENDERER NKScriptContextRemotingProxy Methods
        void NKScriptContextRemotingProxy.NKready()
        {
            var _channel = NKScriptChannel.getChannel(ns);

            context                 = _channel.context;
            _localHandlers[id]      = _channel;
            _channel.singleInstance = true;
            NKEventEmitter.global.once("NKS.SingleInstanceComplete", (string e, string s) =>
            {
                Task.Delay(500).ContinueWith((t) => { NKLogging.log("+[RENDERER] Window Closed"); this.cancelTokenSource.Cancel(); });
            });

            var msg = new NKRemotingMessage();

            msg.command = NKRemotingMessage.Command.NKRemotingReady;
            msg.args    = new string[] { };
            writeObject(asyncPipe, msg);
            NKEventEmitter.global.forward <NKEvent>(eventForwarderFromRenderer);
        }
예제 #21
0
        public async static Task addCorePlatform(NKScriptContext context, Dictionary <string, object> options)
        {
            entryType = (System.Type)options["NKS.Entry"];


            // PROCESS SHOULD BE FIRST CORE PLATFORM PLUGIN
            await NKC_Process.attachToContext(context, options);

            // LOAD REMAINING CORE PLATFORM PLUGINS
            await NKC_FileSystem.attachToContext(context, options);

            //      await NKC_Console.attachToContext(context, options);
            await NKC_Crypto.attachToContext(context, options);

            await NKC_SocketTCP.attachToContext(context, options);

            await NKC_SocketUDP.attachToContext(context, options);

            await NKC_Timer.attachToContext(context, options);
        }
        internal NKScriptValueNative(object value, NKScriptContext context) : base()
        {
            Type t = value.GetType();
            NKScriptChannelProtocol channel = t.getNKScriptChannel();

            if (channel == null)
            {
                channel = t.GetTypeInfo().BaseType.getNKScriptChannel();
                if (channel == null)
                {
                    throw new MissingFieldException("Cannot find channel for NKScriptExport member " + t.Name);
                }
            }

            string pluginNS = channel.ns;
            int    id       = channel.getNativeSeq();

            _instanceid = id;
            string ns = string.Format("{0}[{1}]", pluginNS, id);

            this._channel = channel;

            // super.init(ns: ns, context: channel, origin: nil)
            _context = context;

            this.ns = ns;
            if (origin != null)
            {
                _origin = origin;
            }
            else
            {
                _origin = this;
            }
            // end super init

            channel.addInstance(id, this);
            proxy = bindObject(value);
            syncCreationWithProperties();
        }
예제 #23
0
        private async Task startNodeKitMain(Dictionary<string, object> options)
        {
            NKEventEmitter.isMainProcess = true;

            options.set("NKS.MainThreadScheduler", TaskScheduler.FromCurrentSynchronizationContext());
            options.set("NKS.MainThreadId", Environment.CurrentManagedThreadId);
            var entryClass = options.itemOrDefault("NKS.Entry", typeof(NKC_NodeKit));
      
            context = await NKScriptContextFactory.createContext(options);
         
            // SCRIPT ENGINE LOADED, ADD {NK} NODEKIT
            await NKElectro.Main.addElectro(context, options);
            await NKCore.Main.addCorePlatform(context, options);
            await NKCore.Main.bootCore(context, options);

            // {NK} NODEKIT ADDED, START APPLICATION 
    //        var appjs = await NKStorage.getResourceAsync(entryClass, "index.js", "app");
   //         var script = "function loadapp(){\n" + appjs + "\n}\n" + "loadapp();" + "\n";
    //        await context.NKevaluateJavaScript(script, "io.nodekit.electro.main");

            NKEventEmitter.global.emit<string>("NK.AppReady");
        }
예제 #24
0
        public async static Task addElectroRemoteProxy(NKScriptContext context, Dictionary <string, object> options)
        {
            var optionsDefault = new Dictionary <string, object>
            {
                ["NKS.PluginBridge"]        = NKScriptExportType.NKScriptExport,
                ["NKS.MainThread"]          = true,
                ["NKS.MainThreadId"]        = (int)options["NKS.MainThreadId"],
                ["NKS.MainThreadScheduler"] = (TaskScheduler)options["NKS.MainThreadScheduler"]
            };

            await NKE_BrowserWindow.attachToContext(context, optionsDefault);

            await NKE_WebContents.attachToContext(context, optionsDefault);

            // await context.NKloadPlugin(typeof(NKEDialog), "io.nodekit.electro.dialog", options);

            // NKE_BrowserWindow.attachTo(context);
            // NKE_WebContentsBase.attachTo(context);
            // NKE_Dialog.attachTo(context);
            // NKE_IpcMain.attachTo(context);
            // NKE_Menu.attachTo(context);
            // NKE_Protocol.attachTo(context);
        }
예제 #25
0
        private async Task startNodeKitMain(Dictionary <string, object> options)
        {
            NKEventEmitter.isMainProcess = true;

            options.set("NKS.MainThreadScheduler", TaskScheduler.FromCurrentSynchronizationContext());
            options.set("NKS.MainThreadId", Environment.CurrentManagedThreadId);
            var entryClass = options.itemOrDefault("NKS.Entry", typeof(NKC_NodeKit));

            context = await NKScriptContextFactory.createContext(options);

            // SCRIPT ENGINE LOADED, ADD {NK} NODEKIT
            await NKElectro.Main.addElectro(context, options);

            await NKCore.Main.addCorePlatform(context, options);

            await NKCore.Main.bootCore(context, options);

            // {NK} NODEKIT ADDED, START APPLICATION
            //        var appjs = await NKStorage.getResourceAsync(entryClass, "index.js", "app");
            //         var script = "function loadapp(){\n" + appjs + "\n}\n" + "loadapp();" + "\n";
            //        await context.NKevaluateJavaScript(script, "io.nodekit.electro.main");

            NKEventEmitter.global.emit <string>("NK.AppReady");
        }
 internal static Task attachToContext(NKScriptContext context, Dictionary<string, object> options)
 {
     return context.NKloadPlugin(typeof(NKC_SocketUDP), null, options);
 }
        //  private NKEventEmitter events = NKEventEmitter.global;

        #region NKScriptExport

        internal static Task attachToContext(NKScriptContext context, Dictionary<string, object> options)
        {
            return context.NKloadPlugin(current, null, options);
        }
예제 #28
0
        internal static Task attachToContext(NKScriptContext context, Dictionary <string, object> options)
        {
            var principal = new  NKE_IpcRenderer(context.NKid);

            return(context.NKloadPlugin(principal, null, options));
        }
 // HOST-MAIN PROCESS
 public static NKScriptMessageHandler createClient(string ns, string id, int nativeSeqMax, NKScriptMessage message, NKScriptContext context, CancellationToken cancelToken)
 {
     throw new NotImplementedException();
 }
 internal static Task attachToContext(NKScriptContext context, Dictionary<string, object> options)
 {
     startupOptions = options;
     return context.NKloadPlugin(typeof(NKE_BrowserWindow), null, options);
 }
예제 #31
0
 internal static Task attachToContext(NKScriptContext context, Dictionary <string, object> options)
 {
     return(context.NKloadPlugin(new NKE_Dialog(), null, options));
 }
 internal NKSMSWebViewScriptDelegate(NKScriptContext context)
 {
     this.context = context;
 }
예제 #33
0
        //MAIN
        private NKRemotingProxy(string ns, string id, int nativeSeqMax, NKScriptMessage message, NKScriptContext context, CancellationToken cancelToken)
        {
            this.context        = context;
            this._localHandlers = null;
            this.ns             = ns;

            this.cancelToken = cancelToken;

            var exe  = System.Reflection.Assembly.GetEntryAssembly().Location;
            var path = System.IO.Path.GetDirectoryName(exe);
            ProcessStartInfo startInfo = Process.GetCurrentProcess().StartInfo;

            startInfo.FileName         = exe;
            startInfo.WorkingDirectory = path;
            startInfo.UseShellExecute  = false;

            var syncPipeOut   = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
            var syncPipeIn    = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
            var pipeOutHandle = syncPipeOut.GetClientHandleAsString();
            var pipeInHandle  = syncPipeIn.GetClientHandleAsString();

            this.syncPipeOut = syncPipeOut;
            this.syncPipeIn  = syncPipeIn;

            startInfo.Arguments = "NKR=" + buildInitMessage(pipeOutHandle, pipeInHandle);

            this.id = id;
            process = Process.Start(startInfo);
            NKEventEmitter.global.emit <string>("NKS.ProcessAdded", id, false);
            process.EnableRaisingEvents = true;
            process.Exited += Process_Exited;

            var pipeName  = Convert.ToBase64String(getUniqueKey());
            var asyncPipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.WriteThrough);

            this.asyncPipe = asyncPipe;
            NKScriptChannel.nativeFirstSequence -= 5;

            string nativeFirstSeq = NKScriptChannel.nativeFirstSequence.ToString();

            var handshake = new NKRemotingMessage();

            handshake.command = NKRemotingMessage.Command.NKRemotingHandshake;
            handshake.args    = new string[] { pipeName, ns, id, nativeSeqMax.ToString() };

            syncPipeOut.WriteByte(100);
            syncPipeOut.Flush();
            syncPipeOut.WaitForPipeDrain();
            syncPipeOut.DisposeLocalCopyOfClientHandle();
            syncPipeIn.DisposeLocalCopyOfClientHandle();

            writeObject(syncPipeOut, handshake);
            syncPipeOut.WaitForPipeDrain();

            var handshakeReply = readObject(syncPipeIn);

            if (handshakeReply == null || handshakeReply.command != NKRemotingMessage.Command.NKRemotingHandshake)
            {
                Environment.Exit(911);
            }

            asyncPipe.WaitForConnection();
            cancelToken.Register(requestClientTeardown);
            var nkready = readObject(asyncPipe);

            if (nkready == null || nkready.command != NKRemotingMessage.Command.NKRemotingReady)
            {
                Environment.Exit(910);
            }

            Task.Factory.StartNew((s) => _processServerMessages(asyncPipe), null, cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
            NKEventEmitter.global.forward <NKEvent>(eventForwarderFromMain);
        }
예제 #34
0
        //RENDERER
        private NKRemotingProxy(string[] args)
        {
            NKLogging.log("+Started Renderer in new Process");
            this.context = null;
            this._localHandlers = new Dictionary<string, NKScriptMessageHandler>();
            this.cancelTokenSource = new CancellationTokenSource();
            this.cancelToken = cancelTokenSource.Token;

            var outHandle = args[2];
            var inHandle = args[1];

            var syncPipeOut = new AnonymousPipeClientStream(PipeDirection.Out, outHandle);
            var syncPipeIn = new AnonymousPipeClientStream(PipeDirection.In, inHandle);
            this.syncPipeOut = syncPipeOut;
            this.syncPipeIn = syncPipeIn;

            syncPipeIn.ReadByte();

            var handshake = readObject(syncPipeIn);
            if (handshake.command != NKRemotingMessage.Command.NKRemotingHandshake)
            {
                Environment.Exit(911);
            }

            var pipeName = handshake.args[0];
            ns = handshake.args[1];
            id = handshake.args[2];
             NKScriptChannel.nativeFirstSequence = Int32.Parse(handshake.args[3]);

            handshake.args = new string[] { };
            writeObject(syncPipeOut, handshake);
       
            var asyncPipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough);
            asyncPipe.Connect();
            cancelToken.Register(requestSelfTeardown);

            this.asyncPipe = asyncPipe;
       
            Task.Factory.StartNew((s) => _processClientMessages(), null, cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
  
        }
예제 #35
0
        public object didReceiveScriptMessageSync(NKScriptMessage message)
        {
            // A workaround for when postMessage(undefined)
            if (message.body == null) return false;

            // thread static
            NKScriptChannel._currentContext = this.context;
            object result;

            var body = message.body as Dictionary<string, object>;
            if (body != null && body.ContainsKey("$opcode"))
            {
                string opcode = body["$opcode"] as String;
                int target = Convert.ToInt32(body["$target"] as String);
                if (instances.ContainsKey(target))
                {
                    var obj = instances[target];
                    if (opcode == "-")
                    {
                        if (target == 0)
                        {
                            // Dispose plugin
                            this.unbind();
                            result = true;
                        }
                        else if (instances.ContainsKey(target))
                        {
                            obj.setNKScriptValue(null);
                            result = true;
                        }
                        else
                        {
                            NKLogging.log(String.Format("!Invalid instance id: {0}", target));
                            result = false;
                        }
                    }
                    else if (typeInfo.ContainsProperty(opcode))
                    {
                        // Update property
                        obj.updateNativeProperty(opcode, body["$operand"] as object);
                        result = true;
                    }
                    else if (typeInfo.ContainsMethod(opcode))
                    {
                        // Invoke method
                        result = obj.invokeNativeMethodSync(opcode, body["$operand"] as object[]);
                    }
                    else {
                        NKLogging.log(String.Format("!Invalid member name: {0}", opcode));
                        result = false;
                    }
                }
                else if (opcode == "+")
                {
                    // Create instance
                    var args = body["$operand"] as Array;
                    var ns = String.Format("{0}[{1}]", principal.ns, target);
                    instances[target] = new NKScriptValueNative(ns, this, args);
                    result = true;
                }
                else
                {
                    // else Unknown opcode
                    var obj = principal.plugin as NKScriptMessageHandler;
                    if (obj != null)
                    {
                        result = obj.didReceiveScriptMessageSync(message);
                    }
                    else
                    {
                        // discard unknown message
                        NKLogging.log(String.Format("!Unknown message: {0}", message.body.ToString()));
                        result = false;
                    }
                }
            }
            else
            {
                // null body
                result = false;
            }

            //thread static
            NKScriptChannel._currentContext = null;
            return result;
        }
 // Public constructors
 public NKScriptChannel(NKScriptContext context) : this(context, TaskScheduler.Default)
 {
 }
 public NKScriptChannelRemote(NKScriptContext context, TaskScheduler taskScheduler) : base(context, taskScheduler) { isRemote = true; }
예제 #38
0
 internal static Task attachToContext(NKScriptContext context, Dictionary<string, object> options)
 {
     var principal = new  NKE_IpcRenderer(context.NKid);
     return context.NKloadPlugin(principal, null, options);
 }
 internal static Task attachToContext(NKScriptContext context, Dictionary <string, object> options)
 {
     startupOptions = options;
     return(context.NKloadPlugin(typeof(NKE_BrowserWindow), null, options));
 }
 internal NKSMSWebViewScriptDelegate(NKScriptContext context)
 {
     this.context = context;
 }
예제 #41
0
        //MAIN
        private NKRemotingProxy(string ns, string id, int nativeSeqMax, NKScriptMessage message, NKScriptContext context, CancellationToken cancelToken)
        {
            this.context = context;
            this._localHandlers = null;
            this.ns = ns;

            this.cancelToken = cancelToken;
            
            var exe = System.Reflection.Assembly.GetEntryAssembly().Location;
            var path = System.IO.Path.GetDirectoryName(exe);
            ProcessStartInfo startInfo = Process.GetCurrentProcess().StartInfo;
            startInfo.FileName = exe;
            startInfo.WorkingDirectory = path;
            startInfo.UseShellExecute = false;
         
            var syncPipeOut = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
            var syncPipeIn = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
            var pipeOutHandle = syncPipeOut.GetClientHandleAsString();
            var pipeInHandle = syncPipeIn.GetClientHandleAsString();

            this.syncPipeOut = syncPipeOut;
            this.syncPipeIn = syncPipeIn;
            
            startInfo.Arguments = "NKR=" + buildInitMessage(pipeOutHandle, pipeInHandle);

            this.id = id;
            process = Process.Start(startInfo);
            NKEventEmitter.global.emit<string>("NKS.ProcessAdded", id, false);
            process.EnableRaisingEvents = true;
            process.Exited += Process_Exited;
       
            var pipeName = Convert.ToBase64String(getUniqueKey());
            var asyncPipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.WriteThrough);
            this.asyncPipe = asyncPipe;
            NKScriptChannel.nativeFirstSequence -= 5;

            string nativeFirstSeq = NKScriptChannel.nativeFirstSequence.ToString();
   
            var handshake = new NKRemotingMessage();
            handshake.command = NKRemotingMessage.Command.NKRemotingHandshake;
            handshake.args = new string[] { pipeName, ns, id, nativeSeqMax.ToString() };

            syncPipeOut.WriteByte(100);
            syncPipeOut.Flush();
            syncPipeOut.WaitForPipeDrain();
            syncPipeOut.DisposeLocalCopyOfClientHandle();
            syncPipeIn.DisposeLocalCopyOfClientHandle();

            writeObject(syncPipeOut, handshake);
            syncPipeOut.WaitForPipeDrain();

            var handshakeReply = readObject(syncPipeIn);
            if (handshakeReply == null || handshakeReply.command != NKRemotingMessage.Command.NKRemotingHandshake)
                Environment.Exit(911);

            asyncPipe.WaitForConnection();
            cancelToken.Register(requestClientTeardown);
            var nkready = readObject(asyncPipe);
            if (nkready == null || nkready.command != NKRemotingMessage.Command.NKRemotingReady)
               Environment.Exit(910);
     
            Task.Factory.StartNew((s)=> _processServerMessages(asyncPipe), null, cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
            NKEventEmitter.global.forward<NKEvent>(eventForwarderFromMain);

        }
예제 #42
0
 internal static Task attachToContext(NKScriptContext context, Dictionary <string, object> options)
 {
     return(context.NKloadPlugin(typeof(NKE_IpcMain), null, options));
 }
예제 #43
0
 public MainPage()
 {
     this.InitializeComponent();
     NKSChakraContextFactory.createContext(new Dictionary<string, object>()).ContinueWith(async task => { host = task.Result; await onJavaScriptEngineReady(); });
 }
예제 #44
0
 public NKScriptChannel(NKScriptContext context) : this(context, TaskScheduler.Default) { }
예제 #45
0
        // RENDERER NKScriptContextRemotingProxy Methods
        void NKScriptContextRemotingProxy.NKready()
        {
            var _channel = NKScriptChannel.getChannel(ns);
            context = _channel.context;
            _localHandlers[id] = _channel;
            _channel.singleInstance = true;
            NKEventEmitter.global.once("NKS.SingleInstanceComplete", (string e, string s) =>
            {
                Task.Delay(500).ContinueWith((t) => { NKLogging.log("+[RENDERER] Window Closed"); this.cancelTokenSource.Cancel(); });
            });
            
            var msg = new NKRemotingMessage();
            msg.command = NKRemotingMessage.Command.NKRemotingReady;
            msg.args = new string[] { };
            writeObject(asyncPipe, msg);
            NKEventEmitter.global.forward<NKEvent>(eventForwarderFromRenderer);

        }
 public NKScriptChannel(NKScriptContext context, TaskScheduler taskScheduler)
 {
     _context = context;
     _queue   = taskScheduler;
 }
예제 #47
0
 public NKScriptChannel(NKScriptContext context, TaskScheduler taskScheduler)
 {
     _context = new WeakReference<NKScriptContext>(context);
      this.queue = taskScheduler;
  }
예제 #48
0
 internal static Task attachToContext(NKScriptContext context, Dictionary<string, object> options)
 {
     return context.NKloadPlugin(new NKC_Process(), null, options);
 }
예제 #49
0
 public MainPage()
 {
     this.InitializeComponent();
     NKSChakraContextFactory.createContext(new Dictionary <string, object>()).ContinueWith(async task => { host = task.Result; await onJavaScriptEngineReady(); });
 }
예제 #50
0
        // HOST-MAIN PROCESS
        public static NKScriptMessageHandler createClient(string ns, string id, int nativeSeqMax, NKScriptMessage message, NKScriptContext context, CancellationToken cancelToken)
        {
            var proxy = new NKRemotingProxy(ns, id, nativeSeqMax, message, context, cancelToken);
            var _     = ((NKScriptMessageHandler)proxy).didReceiveScriptMessageSync(message);

            return(proxy);
        }
예제 #51
0
 public NKScriptChannel(NKScriptContext context, TaskScheduler taskScheduler)
 {
     _context   = new WeakReference <NKScriptContext>(context);
     this.queue = taskScheduler;
 }
예제 #52
0
 // HOST-MAIN PROCESS
 public static NKScriptMessageHandler createClient(string ns, string id, int nativeSeqMax, NKScriptMessage message, NKScriptContext context, CancellationToken cancelToken)
 {
     var proxy = new NKRemotingProxy(ns, id, nativeSeqMax, message, context, cancelToken);
     var _ = ((NKScriptMessageHandler)proxy).didReceiveScriptMessageSync(message);
     return proxy;
 }
예제 #53
0
 internal void registerInject(NKScriptContext context)
 {
     this.injected = true;
     this._context = context;
 }