Ejemplo n.º 1
0
        /// <summary>
        /// The start server.
        /// </summary>
        /// <param name="address">
        /// The address.
        /// </param>
        /// <param name="port">
        /// The port.
        /// </param>
        /// <param name="completecallback">
        /// The completecallback.
        /// </param>
        public void StartServer(string address, int port, Action completecallback)
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                Action <string, int, Action> startServer =
                    (a, p, c) => StartServer(a, p, c);

                PostTask(CefThreadId.UI, startServer, address, port, completecallback);

                return;
            }

            if (mServer == null)
            {
                if (!(port >= 1025 && port <= 65535))
                {
                    return;
                }

                Address           = string.IsNullOrWhiteSpace(address) ? DefaultServerAddress : address;
                Port              = port;
                mCompleteCallback = completecallback;


                CefServer.Create(Address, (ushort)Port, DefaultServerBacklog, this);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// The register message routers.
        /// </summary>
        private void RegisterMessageRouters()
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                PostTask(CefThreadId.UI, this.RegisterMessageRouters);
                return;
            }

            BrowserMessageRouter = new CefMessageRouterBrowserSide(new CefMessageRouterConfig());

            // Register message router handlers
            List <object> messageRouterHandlers = IoC.GetAllInstances(typeof(ChromelyMessageRouter)).ToList();

            if ((messageRouterHandlers != null) && (messageRouterHandlers.Count > 0))
            {
                var routerHandlers = messageRouterHandlers.ToList();

                foreach (var item in routerHandlers)
                {
                    ChromelyMessageRouter routerHandler = (ChromelyMessageRouter)item;
                    if (routerHandler.Handler is CefMessageRouterBrowserSide.Handler)
                    {
                        BrowserMessageRouter.AddHandler((CefMessageRouterBrowserSide.Handler)routerHandler.Handler);
                    }
                }
            }
            else
            {
                BrowserMessageRouter.AddHandler(new CefGlueMessageRouterHandler());
            }
        }
 public static Task RunAsync(CefThreadId threadId, Action action)
 {
     if (CefRuntime.CurrentlyOn(threadId))
     {
         action();
         return(TaskHelpers.Completed());
     }
     else
     {
         var tcs = new TaskCompletionSource <FakeVoid>();
         StartNew(threadId, () =>
         {
             try
             {
                 action();
                 tcs.SetResultAsync(default(FakeVoid));
             }
             catch (Exception e)
             {
                 tcs.SetExceptionAsync(e);
             }
         });
         return(tcs.Task);
     }
 }
Ejemplo n.º 4
0
        /// <summary>
        /// The register message routers.
        /// </summary>
        private void RegisterMessageRouters()
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                PostTask(CefThreadId.UI, RegisterMessageRouters);
                return;
            }

            BrowserMessageRouter = new CefMessageRouterBrowserSide(new CefMessageRouterConfig());
            IoC.RegisterInstance <CefMessageRouterBrowserSide>(typeof(CefMessageRouterBrowserSide).FullName, BrowserMessageRouter);

            // Register message router handlers
            var messageRouterHandlers = IoC.GetAllInstances(typeof(ChromelyMessageRouter)).ToList();

            if (messageRouterHandlers.Any())
            {
                var routerHandlers = messageRouterHandlers.ToList();

                foreach (var item in routerHandlers)
                {
                    ChromelyMessageRouter routerHandler = (ChromelyMessageRouter)item;
                    if (routerHandler.Handler is CefMessageRouterBrowserSide.Handler)
                    {
                        BrowserMessageRouter.AddHandler((CefMessageRouterBrowserSide.Handler)routerHandler.Handler);
                    }
                }
            }
            else
            {
                BrowserMessageRouter.AddHandler(new CefGlueMessageRouterHandler());
            }
        }
        protected virtual void RegisterCustomSchemeHandlers()
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                ActionTask.PostTask(CefThreadId.UI, RegisterCustomSchemeHandlers);
                return;
            }

            // Register custom request handlers
            var schemeHandlerList = _handlersResolver?.Invoke(typeof(IChromelySchemeHandler));

            if (schemeHandlerList != null && schemeHandlerList.Any())
            {
                foreach (var schemeHandlerObj in schemeHandlerList)
                {
                    var schemehandler = schemeHandlerObj as IChromelySchemeHandler;
                    if (schemehandler == null ||
                        schemehandler.Scheme == null ||
                        string.IsNullOrWhiteSpace(schemehandler.Scheme.Scheme) ||
                        string.IsNullOrWhiteSpace(schemehandler.Scheme.Host))
                    {
                        continue;
                    }

                    _requestSchemeProvider.Add(schemehandler.Scheme);
                    var schemeHandlerFactory = schemehandler.HandlerFactory as CefSchemeHandlerFactory;
                    CefRuntime.RegisterSchemeHandlerFactory(schemehandler.Scheme.Scheme, schemehandler.Scheme.Host, schemeHandlerFactory);
                }
            }
        }
    protected virtual void RegisterCustomSchemeHandlers()
    {
        if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
        {
            ActionTask.PostTask(CefThreadId.UI, RegisterCustomSchemeHandlers);
            return;
        }

        // Register custom request handlers
        var schemeHandlerList = _handlersResolver?.Invoke(typeof(IChromelySchemeHandler));

        if (schemeHandlerList is not null && schemeHandlerList.Any())
        {
            foreach (var schemeHandlerObj in schemeHandlerList)
            {
                if (schemeHandlerObj is not IChromelySchemeHandler schemehandler ||
                    schemehandler.Scheme is null ||
                    !schemehandler.Scheme.ValidSchemeHost)
                {
                    continue;
                }

                _requestSchemeProvider.Add(schemehandler.Scheme);
                var schemeHandlerFactory = schemehandler.HandlerFactory as CefSchemeHandlerFactory;
                if (schemeHandlerFactory is not null)
                {
                    CefRuntime.RegisterSchemeHandlerFactory(schemehandler.Scheme.Scheme, schemehandler.Scheme.Host, schemeHandlerFactory);
                }
            }
        }
    }
        protected virtual void MessageRouterHandlers()
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                ActionTask.PostTask(CefThreadId.UI, MessageRouterHandlers);
                return;
            }

            _browserMessageRouter = new CefMessageRouterBrowserSide(new CefMessageRouterConfig());

            // Register message router handlers
            var messageRouterHandlers = _handlersResolver?.Invoke(typeof(IChromelyMessageRouter))?.ToList();

            if (messageRouterHandlers != null && messageRouterHandlers.Any())
            {
                foreach (var handler in messageRouterHandlers)
                {
                    var router = handler as CefMessageRouterBrowserSide.Handler;
                    if (router != null)
                    {
                        _browserMessageRouter.AddHandler(router);
                    }
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// The register AJAX scheme handlers.
        /// </summary>
        private void RegisterAjaxSchemeHandlers()
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                PostTask(CefThreadId.UI, RegisterAjaxSchemeHandlers);
                return;
            }

            // Register AJAX scheme handlers
            var schemeSchemes = _config?.UrlSchemes.GetAllAjaxSchemes();

            if (schemeSchemes != null && schemeSchemes.Any())
            {
                foreach (var item in schemeSchemes)
                {
                    bool isDefault = true;
                    if (!string.IsNullOrWhiteSpace(item.Name))
                    {
                        var schemeObj            = _container.GetInstance(typeof(IChromelySchemeHandlerFactory), item.Name);
                        var schemeHandlerFactory = schemeObj as CefSchemeHandlerFactory;
                        if (schemeHandlerFactory != null)
                        {
                            isDefault = false;
                            CefRuntime.RegisterSchemeHandlerFactory(item.Scheme, item.Host, schemeHandlerFactory);
                        }
                    }

                    if (isDefault)
                    {
                        CefRuntime.RegisterSchemeHandlerFactory(item.Scheme, item.Host, new ExternalRequestSchemeHandlerFactory());
                    }
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// The start server.
        /// </summary>
        /// <param name="port">
        /// The port.
        /// </param>
        /// <param name="completecallback">
        /// The completecallback.
        /// </param>
        public void StartServer(int port, Action completecallback)
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                Action <int, Action> startServer =
                    (p, c) => this.StartServer(p, c);

                this.PostTask(CefThreadId.UI, startServer, port, completecallback);

                return;
            }

            if (this.mServer == null)
            {
                if (!(port >= 1025 && port <= 65535))
                {
                    return;
                }

                this.Address           = DefaultServerAddress;
                this.Port              = port;
                this.mCompleteCallback = completecallback;

                CefServer.Create(this.Address, (ushort)this.Port, DefaultServerBacklog, this);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// The register message routers.
        /// </summary>
        private void RegisterMessageRouters()
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                PostTask(CefThreadId.UI, RegisterMessageRouters);
                return;
            }

            BrowserMessageRouter = new CefMessageRouterBrowserSide(new CefMessageRouterConfig());

            // Register message router handlers
            var messageRouterHandlers = _container.GetAllInstances(typeof(IChromelyMessageRouter));

            if (messageRouterHandlers == null && messageRouterHandlers.Any())
            {
                foreach (var handler in messageRouterHandlers)
                {
                    var router = handler as CefMessageRouterBrowserSide.Handler;
                    if (router != null)
                    {
                        BrowserMessageRouter.AddHandler(router);
                    }
                }
            }
            else
            {
                BrowserMessageRouter.AddHandler(new CefGlueMessageRouterHandler(_requestTaskRunner));
            }
        }
Ejemplo n.º 11
0
 internal static void RequireRendererThread()
 {
     if (!CefRuntime.CurrentlyOn(CefThreadId.Renderer))
     {
         throw new InvalidOperationException("This method should be called on CEF renderer thread.");
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// The register resource handlers.
        /// </summary>
        private void RegisterResourceHandlers()
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                PostTask(CefThreadId.UI, RegisterResourceHandlers);
                return;
            }

            // Register resource handlers
            var resourceSchemes = _config?.UrlSchemes.GetAllResouceSchemes();

            if (resourceSchemes != null && resourceSchemes.Any())
            {
                foreach (var item in resourceSchemes)
                {
                    bool isDefault = true;
                    if (!string.IsNullOrWhiteSpace(item.Name))
                    {
                        var resourceObj            = _container.GetInstance(typeof(IChromelyResourceHandlerFactory), item.Name);
                        var resourceHandlerFactory = resourceObj as CefSchemeHandlerFactory;
                        if (resourceHandlerFactory != null)
                        {
                            isDefault = false;
                            CefRuntime.RegisterSchemeHandlerFactory(item.Scheme, item.Host, resourceHandlerFactory);
                        }
                    }

                    if (isDefault)
                    {
                        CefRuntime.RegisterSchemeHandlerFactory(item.Scheme, item.Host, new CefGlueResourceSchemeHandlerFactory());
                    }
                }
            }
        }
 private static bool EnsureOnRendererThread()
 {
     if (!CefRuntime.CurrentlyOn(CefThreadId.Renderer))
     {
         Logger.Error("Current thread is not the render thread");
         return(false);
     }
     return(true);
 }
Ejemplo n.º 14
0
        private void RegisterMessageRouter()
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                PostTask(CefThreadId.UI, this.RegisterMessageRouter);
                return;
            }

            // window.cefQuery({ request: 'my_request', onSuccess: function(response) { console.log(response); }, onFailure: function(err,msg) { console.log(err, msg); } });
            DemoApp.BrowserMessageRouter = new CefMessageRouterBrowserSide(new CefMessageRouterConfig());
            DemoApp.BrowserMessageRouter.AddHandler(new DemoMessageRouterHandler());
        }
Ejemplo n.º 15
0
 /*
  * I think it is possible to RegisterMessageRouter prior to an event being added but after the other handler objects are made
  * The MessageRouterHandler will do a lookup of registered events every time
  **/
 private void RegisterMessageRouter()
 {
     Debug.WriteLine(DBGPREFIX + "Message Router, attempting registration");
     if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
     {
         Debug.WriteLine(DBGPREFIX + "Message Router, creating task on UI Thread");
         CefRuntime.PostTask(CefThreadId.UI, new ActionTask(RegisterMessageRouter));
         return;
     }
     // window.cefQuery({ request: 'my_request', onSuccess: function(response) { console.log(response); }, onFailure: function(err,msg) { console.log(err, msg); } });
     _messageRouter.AddHandler(MessageRouterHandler);
     Debug.WriteLine(DBGPREFIX + "Message Router, registered");
 }
        protected void NativeHost_CreateAndShowWindow()
        {
            if (_config.Platform != ChromelyPlatform.Windows)
            {
                if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
                {
                    ActionTask.PostTask(CefThreadId.UI, NativeHost_CreateAndShowWindow);
                    return;
                }
            }

            _nativeHost?.CreateWindow(_config.WindowOptions, _config.DebuggingMode);
        }
Ejemplo n.º 17
0
        private void CreateMainWindow()
        {
            if (_config.Platform != ChromelyPlatform.Windows)
            {
                if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
                {
                    PostTask(CefThreadId.UI, CreateMainWindow);
                    return;
                }
            }

            _mainWindow = CreateMainView();
        }
Ejemplo n.º 18
0
        /// <summary>
        /// The run complete callback.
        /// </summary>
        /// <param name="isRunning">
        /// The is running.
        /// </param>
        private void RunCompleteCallback(bool isRunning)
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                Action <bool> run =
                    (f) => RunCompleteCallback(f);

                PostTask(CefThreadId.UI, run, isRunning);

                return;
            }

            mCompleteCallback?.Invoke();
        }
Ejemplo n.º 19
0
        private void RegisterMessageRouter()
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                PostTask(CefThreadId.UI, this.RegisterMessageRouter);
                return;
            }


            BrowserMessageRouter          = new CefMessageRouterBrowserSide(new CefMessageRouterConfig());
            _queryHandler                 = new WorkerCefMessageRouterHandler();
            _queryHandler.OnBrowserQuery += Handler_OnBrowserQuery;
            BrowserMessageRouter.AddHandler(_queryHandler);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Executes the task on the selected CEF thread.
        /// </summary>
        /// <param name="threadId">The thread identifier.</param>
        /// <param name="action">The action.</param>
        /// <exception cref="System.ArgumentNullException">action</exception>
        public static void ExecuteTask(CefThreadId threadId, Action action)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            if (!CefRuntime.CurrentlyOn(threadId))
            {
                CefRuntime.PostTask(threadId, new ActionTask(action));
            }
            else
            {
                action();
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// The run complete callback.
        /// </summary>
        /// <param name="isRunning">
        /// The is running.
        /// </param>
        private void RunCompleteCallback(bool isRunning)
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                Action <bool> run =
                    (f) => this.RunCompleteCallback(f);

                this.PostTask(CefThreadId.UI, run, isRunning);

                return;
            }

            if (this.mCompleteCallback != null)
            {
                this.mCompleteCallback.Invoke();
            }
        }
Ejemplo n.º 22
0
        private void RegisterMessageRouter()
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                PostTask(CefThreadId.UI, this.RegisterMessageRouter);
                return;
            }


            BrowserMessageRouter          = new CefMessageRouterBrowserSide(new CefMessageRouterConfig());
            _queryHandler                 = new WorkerCefMessageRouterHandler();
            _queryHandler.OnBrowserQuery += Handler_OnBrowserQuery;
            BrowserMessageRouter.AddHandler(_queryHandler);
            var myFactory = new MySchemeHandlerFactory(_staticResourceStorage, this);

            CefRuntime.RegisterSchemeHandlerFactory("http", _domainId, myFactory);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// The stop server.
        /// </summary>
        /// <param name="completecallback">
        /// The completecallback.
        /// </param>
        public void StopServer(Action completecallback)
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                Action <Action> stopServer =
                    (c) => this.StopServer(c);

                this.PostTask(CefThreadId.UI, stopServer, completecallback);

                return;
            }

            if (this.mServer != null)
            {
                this.mCompleteCallback = completecallback;
                this.mServer.Shutdown();
            }
        }
    protected virtual void RegisterDefaultSchemeHandlers()
    {
        if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
        {
            ActionTask.PostTask(CefThreadId.UI, RegisterDefaultSchemeHandlers);
            return;
        }

        if (_handlersResolver is null)
        {
            return;
        }

        // Register default resource/reguest handlers
        IDictionary <UrlSchemeType, Type> urlTypesMapper = new Dictionary <UrlSchemeType, Type>
        {
            { UrlSchemeType.LocalResource, typeof(IDefaultResourceCustomHandler) },
            { UrlSchemeType.FolderResource, typeof(IDefaultResourceCustomHandler) },
            { UrlSchemeType.AssemblyResource, typeof(IDefaultAssemblyResourceCustomHandler) },
            { UrlSchemeType.LocalRequest, typeof(IDefaultRequestCustomHandler) },
            { UrlSchemeType.Owin, typeof(IDefaultOwinCustomHandler) },
            { UrlSchemeType.ExternalRequest, typeof(IDefaultExernalRequestCustomHandler) }
        };

        foreach (var urlType in urlTypesMapper)
        {
            var handler = _handlersResolver.GetDefaultHandler(typeof(CefSchemeHandlerFactory), urlType.Value);

            if (handler is CefSchemeHandlerFactory schemeHandlerFactory)
            {
                var schemes = _config?.UrlSchemes.GetSchemesByType(urlType.Key);
                if (schemes is not null && schemes.Any())
                {
                    foreach (var item in schemes)
                    {
                        _requestSchemeProvider.Add(item);
                        CefRuntime.RegisterSchemeHandlerFactory(item.Scheme, item.Host, schemeHandlerFactory);
                    }
                }
            }
        }
    }
        /// <summary>
        /// Calls back into V8 in response to either:
        /// - a local function response message
        /// - a local event fired message
        /// - an exception while making a local function call
        /// Will switch to the Renderer thread if needed.
        /// </summary>
        /// <param name="call"></param>
        /// <param name="result"></param>
        /// <param name="errorCode"></param>
        /// <param name="error"></param>
        public void LocalCallbackInvoked(LocalRenderCallInfo call, object result, int errorCode, string error)
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.Renderer))
            {
                // Call completed received from remote process, so currently are on the IO method. Marshal to the renderer to callback into V8
                CefRuntime.PostTask(CefThreadId.Renderer,
                                    new ActionCallbackTask(() => LocalCallbackInvoked(call, result, errorCode, error)));
                return;
            }

            var msg = call.RequestMessage;

            Logger.Info("LocalCallbackInvoked MsgType {0} Plugin {1} Member {2}",
                        msg.MessageType, msg.PluginId, msg.MemberName);

            // Already on the render thread (e.g. local plugin event triggered by call into function from JS, or function invoke failed
            try
            {
                var context = GetContextById(call.RequestMessage.ContextId);
                if (!call.IsRetained)
                {
                    _pendingCallbacks.Remove(call);
                }
                if (context != null && call.Callback != null)
                {
                    call.Callback.Invoke(this, context, result, errorCode, error);
                }
                if (!call.IsRetained)
                {
                    call.Dispose();
                }
            }
            catch (Exception exception)
            {
                Logger.Error("LocalCallbackInvoked Failed MsgType {0} Plugin {1} Member {2}: {3}",
                             call.RequestMessage.MessageType,
                             call.RequestMessage.PluginId,
                             call.RequestMessage.MemberName,
                             exception);
            }
        }
            /// <summary>
            /// Notify the associated JavaScript onFailure callback that the query has
            /// failed with the specified |error_code| and |error_message|.
            /// </summary>
            public void Failure(int errorCode, string errorMessage)
            {
                if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
                {
                    // Must execute on the UI thread to access member variables.
                    Helpers.PostTask(CefThreadId.UI,
                                     Helpers.Apply(this.Failure, errorCode, errorMessage)
                                     );
                    return;
                }

                if (_router != null)
                {
                    Helpers.PostTaskUncertainty(CefThreadId.UI,
                                                Helpers.Apply(_router.OnCallbackFailure, _browserId, _queryId, errorCode, errorMessage)
                                                );

                    // Failure always invalidates the callback.
                    _router = null;
                }
            }
        // Cancel all pending queries associated with either |browser| or |handler|.
        // If both |browser| and |handler| are NULL all pending queries will be
        // canceled. Set |notify_renderer| to true if the renderer should be notified.
        private void CancelPendingFor(CefBrowser browser, Handler handler, bool notifyRenderer)
        {
            if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
            {
                // Must execute on the UI thread.
                Helpers.PostTask(CefThreadId.UI,
                                 Helpers.Apply(this.CancelPendingFor, browser, handler, notifyRenderer)
                                 );
                return;
            }

            if (_browserQueryInfoMap.IsEmpty)
            {
                return;
            }

            BrowserInfoMap.Visitor visitor = (int browserId, long queryId, QueryInfo info, ref bool remove) =>
            {
                if (handler == null || info.Handler == handler)
                {
                    remove = true;
                    CancelQuery(queryId, info, notifyRenderer);
                    info.Dispose();
                }
                return(true);
            };

            if (browser != null)
            {
                // Cancel all queries associated with the specified browser.
                _browserQueryInfoMap.FindAll(browser.Identifier, visitor);
            }
            else
            {
                // Cancel all queries for all browsers.
                _browserQueryInfoMap.FindAll(visitor);
            }
        }
            /// <summary>
            /// Notify the associated JavaScript onSuccess callback that the query has
            /// completed successfully with the specified |response|.
            /// </summary>
            public void Success(string response)
            {
                if (!CefRuntime.CurrentlyOn(CefThreadId.UI))
                {
                    Helpers.PostTask(CefThreadId.UI,
                                     Helpers.Apply(this.Success, response)
                                     );
                    return;
                }

                if (_router != null)
                {
                    Helpers.PostTaskUncertainty(CefThreadId.UI,
                                                Helpers.Apply(_router.OnCallbackSuccess, _browserId, _queryId, response)
                                                );

                    if (!_persistent)
                    {
                        // Non-persistent callbacks are only good for a single use.
                        _router = null;
                    }
                }
            }