private void Register()
        {
            var hostName   = new Regex("[^a-zA-Z0-9]").Replace(_package.Manifest.Name, "") + "." + Domain;
            var packageUrl = SchemeName + "://" + hostName;

            // Set up by-passes between the package url and gs.com domain
            CefRuntime.AddCrossOriginWhitelistEntry(packageUrl, "http", Domain, true);
            CefRuntime.AddCrossOriginWhitelistEntry(packageUrl, "https", Domain, true);
            CefRuntime.AddCrossOriginWhitelistEntry(packageUrl, "ws", Domain, true);
            CefRuntime.AddCrossOriginWhitelistEntry(packageUrl, "wss", Domain, true);

            if (_package.Manifest.CORSBypassList != null)
            {
                foreach (var bypassEntry in _package.Manifest.CORSBypassList)
                {
                    if (!(string.IsNullOrEmpty(bypassEntry.TargetDomain) && bypassEntry.AllowTargetSubdomains))
                    {
                        CefRuntime.AddCrossOriginWhitelistEntry(bypassEntry.SourceUrl, bypassEntry.Protocol, bypassEntry.TargetDomain, bypassEntry.AllowTargetSubdomains);
                    }
                    else
                    {
                        Logger.Warn("CORS bypass from {0} to domain {0} can't be set.", bypassEntry.SourceUrl, bypassEntry.TargetDomain ?? string.Empty);
                    }
                }
            }

            if (!CefRuntime.RegisterSchemeHandlerFactory(SchemeName, hostName.ToLower(), this))
            {
                Logger.Error(string.Format("Packaged application {0}: could not register scheme handler factory", _package.Manifest.Name));
                return;
            }
            _baseUrl = packageUrl;
        }
Exemple #2
0
        /// <summary>
        /// Registers the schemes.
        /// </summary>
        private void RegisterSchemes()
        {
            // TODO: Temp.
            CefRuntime.RegisterSchemeHandlerFactory("http", "test.test.test", new DefaultAppSchemeHandlerFactory());

            GeneralLog.Info("Schemes registered.");
        }
Exemple #3
0
        /// <summary>
        /// The register scheme handlers.
        /// </summary>
        private void RegisterSchemeHandlers()
        {
            // Register scheme handlers
            var schemeSchemes = _config?.UrlSchemes.GetAllCustomSchemes();

            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 CefGlueHttpSchemeHandlerFactory(_config, _requestTaskRunner));
                    }
                }
            }
        }
        // Main entry point when called by vvvv
        void IStartable.Start()
        {
            CefRuntime.Load();

            var cefSettings = new CefSettings();

            cefSettings.WindowlessRenderingEnabled = true;
            cefSettings.PackLoadingDisabled        = false;
            cefSettings.MultiThreadedMessageLoop   = true;
            cefSettings.BrowserSubprocessPath      = Assembly.GetExecutingAssembly().Location;
            cefSettings.CommandLineArgsDisabled    = false;
            cefSettings.IgnoreCertificateErrors    = true;
            //// We do not meet the requirements - see cef_sandbox_win.h
            //cefSettings.NoSandbox = true;
#if DEBUG
            cefSettings.LogSeverity = CefLogSeverity.Error;
            // Set to true to debug DOM / JavaScript
            cefSettings.SingleProcess = false;
#else
            cefSettings.LogSeverity = CefLogSeverity.Disable;
#endif

            var args     = Environment.GetCommandLineArgs();
            var mainArgs = new CefMainArgs(args);
            CefRuntime.Initialize(mainArgs, cefSettings, new HTMLTextureApp(), IntPtr.Zero);

            var schemeName = "cef";
            if (!CefRuntime.RegisterSchemeHandlerFactory(SchemeHandlerFactory.SCHEME_NAME, null, new SchemeHandlerFactory()))
            {
                throw new Exception(string.Format("Couldn't register custom scheme factory for '{0}'.", schemeName));
            }
        }
        /// <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());
                    }
                }
            }
        }
        /// <summary>
        /// The register scheme handlers.
        /// </summary>
        private void RegisterSchemeHandlers()
        {
            // Register scheme handlers
            var schemeHandlerObjs = IoC.GetAllInstances(typeof(SchemeHandler));

            if (schemeHandlerObjs != null)
            {
                var schemeHandlers = schemeHandlerObjs.ToList();

                foreach (var item in schemeHandlers)
                {
                    if (item is SchemeHandler handler)
                    {
                        if (handler.HandlerFactory == null)
                        {
                            if (handler.UseDefaultResource)
                            {
                                CefRuntime.RegisterSchemeHandlerFactory(handler.SchemeName, handler.DomainName, new CefGlueResourceSchemeHandlerFactory());
                            }

                            if (handler.UseDefaultHttp)
                            {
                                CefRuntime.RegisterSchemeHandlerFactory(handler.SchemeName, handler.DomainName, new CefGlueHttpSchemeHandlerFactory());
                                //CefRuntime.AddCrossOriginWhitelistEntry(handler.SchemeName+"://127.0.0.1", handler.SchemeName, "", true);
                            }
                        }
                        else if (handler.HandlerFactory is CefSchemeHandlerFactory)
                        {
                            CefRuntime.RegisterSchemeHandlerFactory(handler.SchemeName, handler.DomainName, (CefSchemeHandlerFactory)handler.HandlerFactory);
                        }
                    }
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// The register scheme handlers.
        /// </summary>
        private void RegisterSchemeHandlers()
        {
            // Register scheme handlers
            var schemeHandlerObjs = IoC.GetAllInstances(typeof(ChromelySchemeHandler));

            if (schemeHandlerObjs != null)
            {
                var schemeHandlers = schemeHandlerObjs.ToList();

                foreach (var item in schemeHandlers)
                {
                    if (item is ChromelySchemeHandler handler)
                    {
                        if (handler.HandlerFactory == null)
                        {
                            if (handler.UseDefaultResource)
                            {
                                CefRuntime.RegisterSchemeHandlerFactory(handler.SchemeName, handler.DomainName, new CefGlueResourceSchemeHandlerFactory());
                            }

                            if (handler.UseDefaultHttp)
                            {
                                CefRuntime.RegisterSchemeHandlerFactory(handler.SchemeName, handler.DomainName, new CefGlueHttpSchemeHandlerFactory());
                            }
                        }
                        else if (handler.HandlerFactory is CefSchemeHandlerFactory)
                        {
                            CefRuntime.RegisterSchemeHandlerFactory(handler.SchemeName, handler.DomainName, (CefSchemeHandlerFactory)handler.HandlerFactory);
                        }
                    }
                }
            }
        }
    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);
                }
            }
        }
    }
Exemple #9
0
        /// <summary>
        /// The register resource handlers.
        /// </summary>
        private void RegisterResourceHandlers()
        {
            // 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 void RegisterSchemes()
 {
     // register custom scheme handler
     CefRuntime.RegisterSchemeHandlerFactory("http", DumpRequestDomain, new DemoAppSchemeHandlerFactory());
     //CefRuntime.RegisterSchemeHandlerFactory("http", DumpRequestDomain, new TestDumpRequestHandlerFactory());
     // CefRuntime.AddCrossOriginWhitelistEntry("http://localhost", "http", "", true);
 }
        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);
                }
            }
        }
Exemple #12
0
        private static int Main(string[] args)
        {
            try
            {
                CefRuntime.Load();
            }
            catch (DllNotFoundException ex)
            {
                MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(1);
            }
            catch (CefRuntimeException ex)
            {
                MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(2);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(3);
            }

            var mainArgs = new CefMainArgs(args);
            var app      = new DemoApp();

            var exitCode = CefRuntime.ExecuteProcess(mainArgs, app);

            if (exitCode != -1)
            {
                return(exitCode);
            }

            var settings = new CefSettings
            {
                // BrowserSubprocessPath = @"D:\fddima\Projects\Xilium\Xilium.CefGlue\CefGlue.Demo\bin\Release\Xilium.CefGlue.Demo.exe",
                SingleProcess            = false,
                MultiThreadedMessageLoop = true,
                LogSeverity         = CefLogSeverity.Disable,
                LogFile             = "CefGlue.log",
                RemoteDebuggingPort = 7777,
            };

            CefRuntime.Initialize(mainArgs, settings, app);
            CefRuntime.RegisterSchemeHandlerFactory("http", "server", new MySchemeHandlerFactory());

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (!settings.MultiThreadedMessageLoop)
            {
                Application.Idle += (sender, e) => { CefRuntime.DoMessageLoopWork(); };
            }

            Application.Run(new MainForm());

            CefRuntime.Shutdown();
            return(0);
        }
Exemple #13
0
        public int Run(string[] args)
        {
            CefRuntime.Load();

            var settings = new CefSettings();

            settings.MultiThreadedMessageLoop = CefRuntime.Platform == CefRuntimePlatform.Windows;
            settings.ReleaseDCheckEnabled     = true;
            settings.LogSeverity         = CefLogSeverity.Verbose;
            settings.LogFile             = "cef.log";
            settings.ResourcesDirPath    = System.IO.Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetEntryAssembly().CodeBase).LocalPath);
            settings.RemoteDebuggingPort = 20480;

            var argv = args;

            if (CefRuntime.Platform != CefRuntimePlatform.Windows)
            {
                argv = new string[args.Length + 1];
                Array.Copy(args, 0, argv, 1, args.Length);
                argv[0] = "-";
            }

            var mainArgs = new CefMainArgs(argv);
            var app      = new DemoCefApp();

            var exitCode = CefRuntime.ExecuteProcess(mainArgs, app);

            Console.WriteLine("CefRuntime.ExecuteProcess() returns {0}", exitCode);
            if (exitCode != -1)
            {
                return(exitCode);
            }



            CefRuntime.Initialize(mainArgs, settings, app);

            // register custom scheme handler
            CefRuntime.RegisterSchemeHandlerFactory("http", DumpRequestDomain, new DemoAppSchemeHandlerFactory());

            PlatformInitialize();

            var mainMenu = CreateMainMenu();

            _mainView = CreateMainView(mainMenu);
            _mainView.NewTab(HomeUrl);

            PlatformRunMessageLoop();

            _mainView.Dispose();
            _mainView = null;

            CefRuntime.Shutdown();

            PlatformShutdown();
            return(0);
        }
Exemple #14
0
        public static IResourceProvider <IDisposable> GetRuntimeProvider()
        {
            return(ResourceProvider.New(() =>
            {
                if (Interlocked.Increment(ref initCount) == 1)
                {
                    CefRuntime.Load();

                    var cefSettings = new CefSettings();
                    cefSettings.WindowlessRenderingEnabled = true;
                    cefSettings.PackLoadingDisabled = false;
                    cefSettings.MultiThreadedMessageLoop = true;
                    cefSettings.BrowserSubprocessPath = typeof(WebRendererApp).Assembly.Location;
                    cefSettings.CommandLineArgsDisabled = false;
                    cefSettings.IgnoreCertificateErrors = true;
                    //// We do not meet the requirements - see cef_sandbox_win.h
                    //cefSettings.NoSandbox = true;
#if DEBUG
                    cefSettings.LogSeverity = CefLogSeverity.Error;
#else
                    cefSettings.LogSeverity = CefLogSeverity.Disable;
#endif

                    // Check if we're in package (different folder layout)
                    var filename = Path.GetFileName(cefSettings.BrowserSubprocessPath);
                    var toolsPath = Path.Combine(Path.GetDirectoryName(cefSettings.BrowserSubprocessPath), "..", "..", "runtimes", "win-x64", "native", filename);
                    if (File.Exists(toolsPath))
                    {
                        cefSettings.BrowserSubprocessPath = toolsPath;
                    }

                    var args = Environment.GetCommandLineArgs();
                    var mainArgs = new CefMainArgs(args);
                    CefRuntime.Initialize(mainArgs, cefSettings, new WebRendererApp(), IntPtr.Zero);

                    var schemeName = "cef";
                    if (!CefRuntime.RegisterSchemeHandlerFactory(SchemeHandlerFactory.SCHEME_NAME, null, new SchemeHandlerFactory()))
                    {
                        throw new Exception(string.Format("Couldn't register custom scheme factory for '{0}'.", schemeName));
                    }

                    //return Disposable.Create(() => CefRuntime.Shutdown());
                }
                else
                {
                }
                return Disposable.Empty;
            }).ShareInParallel());
        }
        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);
        }
Exemple #16
0
        public bool InitializeBrowser()
        {
            AllocConsole();
            CefRuntime.Load();

            var settings = new CefSettings();

            settings.MultiThreadedMessageLoop = CefRuntime.Platform == CefRuntimePlatform.Windows;
            settings.ReleaseDCheckEnabled     = true;
            settings.LogSeverity = CefLogSeverity.Info;
            settings.LogFile     = "cef.log";
            //settings.ResourcesDirPath = System.IO.Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetEntryAssembly().CodeBase).LocalPath);
            settings.RemoteDebuggingPort = 20480;
            settings.Locale = "zh-CN";
            var a = Config.JsFunctionAssembly;


            var mainArgs = new CefMainArgs(new string[0]);
            var app      = new DemoCefApp();

            var exitCode = CefRuntime.ExecuteProcess(mainArgs, app);

            Console.WriteLine("CefRuntime.ExecuteProcess() returns {0}", exitCode);
            //返回值-1为成功
            if (exitCode != -1)
            {
                return(false);
            }

            //初始化
            CefRuntime.Initialize(mainArgs, settings, app);
            CefRuntime.RegisterSchemeHandlerFactory("http", DumpRequestDomain, new DemoAppSchemeHandlerFactory());
            browserCtl        = new CefWebBrowser();
            browserCtl.Parent = this.panel1;
            browserCtl.Dock   = DockStyle.Fill;
            browserCtl.BringToFront();
            var browser = browserCtl.WebBrowser;

            browser.StartUrl = HomeUrl;

            //navBox.Attach(browser);

            return(true);
        }
        public void Start()
        {
            ManualResetEventSlim disposedEvent = new ManualResetEventSlim();

            dispatcher.Invoke(new Action(() =>
            {
                CefRuntime.Load();
                CefMainArgs cefMainArgs         = new CefMainArgs(IntPtr.Zero, new String[0]);
                BrowserRuntimeSettings settings = BrowserSettings.Instance.RuntimeSettings;

                isMultiThreadedMessageLoop = settings.MultiThreadedMessageLoop;

                CefSettings cefSettings = new CefSettings
                {
                    BrowserSubprocessPath   = @"plugins\CLRHostPlugin\CLRBrowserSourcePlugin\CLRBrowserSourcePipe.exe",
                    CachePath               = settings.CachePath,
                    CommandLineArgsDisabled = settings.CommandLineArgsDisabled,
                    IgnoreCertificateErrors = settings.IgnoreCertificateErrors,
                    JavaScriptFlags         = settings.JavaScriptFlags,
                    Locale                     = settings.Locale,
                    LocalesDirPath             = settings.LocalesDirPath,
                    LogFile                    = settings.LogFile,
                    LogSeverity                = settings.LogSeverity,
                    MultiThreadedMessageLoop   = settings.MultiThreadedMessageLoop,
                    PersistSessionCookies      = settings.PersistSessionCookies,
                    ProductVersion             = settings.ProductVersion,
                    ReleaseDCheckEnabled       = settings.ReleaseDCheckEnabled,
                    RemoteDebuggingPort        = settings.RemoteDebuggingPort,
                    ResourcesDirPath           = settings.ResourcesDirPath,
                    SingleProcess              = settings.SingleProcess,
                    UncaughtExceptionStackSize = settings.UncaughtExceptionStackSize
                };

                BrowserApp browserApp = new BrowserApp(settings.CommandLineArgsDisabled ? new String[0] : settings.CommandLineArguments);

                CefRuntime.ExecuteProcess(cefMainArgs, browserApp);
                CefRuntime.Initialize(cefMainArgs, cefSettings, browserApp);

                CefRuntime.RegisterSchemeHandlerFactory("local", null, new AssetSchemeHandlerFactory());
                CefRuntime.RegisterSchemeHandlerFactory("http", "absolute", new AssetSchemeHandlerFactory());
            }));

            PluginManager.Initialize();
        }
    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>
        /// 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)
                    {
                        if (item.UrlSchemeType == UrlSchemeType.Resource)
                        {
                            CefRuntime.RegisterSchemeHandlerFactory(item.Scheme, item.Host, new CefGlueResourceSchemeHandlerFactory());
                        }
                        else if (item.UrlSchemeType == UrlSchemeType.AssemblyResource)
                        {
                            CefRuntime.RegisterSchemeHandlerFactory(item.Scheme, item.Host, new CefGlueAssemblyResourceSchemeHandlerFactory(_config));
                        }
                    }
                }
            }
        }
        private void RegisterSchemeHandlers()
        {
            // Register scheme handlers
            IEnumerable <object> schemeHandlerObjs = IoC.GetAllInstances(typeof(ChromelySchemeHandler));

            if (schemeHandlerObjs != null)
            {
                var schemeHandlers = schemeHandlerObjs.ToList();

                foreach (var item in schemeHandlers)
                {
                    if (item is ChromelySchemeHandler)
                    {
                        ChromelySchemeHandler handler = (ChromelySchemeHandler)item;
                        if (handler.HandlerFactory is CefSchemeHandlerFactory)
                        {
                            CefRuntime.RegisterSchemeHandlerFactory(handler.SchemeName, handler.DomainName, (CefSchemeHandlerFactory)handler.HandlerFactory);
                        }
                    }
                }
            }
        }
Exemple #21
0
        public int Run(CefConfig config)
        {
            this.config = config;
            var res = Instance.GetScreenResolution();

            if (config.FullScreen || config.Kiosk)
            {
                config.Width  = (int)(ScaleFactor * res.Width) - 1;
                config.Height = (int)(ScaleFactor * res.Height);
            }
            else
            {
                config.Width  = (int)(config.Width > 0 ? config.Width * ScaleFactor : res.Width * .75);
                config.Height = (int)(config.Height > 0 ? config.Height * ScaleFactor : res.Height * .75);
            }

            if (config.HideConsoleWindow && !config.Verbose)
            {
                Instance.HideConsoleWindow();
            }

            var factory = WinapiHostFactory.Init(config.Icon);

            using (window = factory.CreateWindow(
                       () => new CefGlueHost(config),
                       config.WindowTitle,
                       constructionParams: new FrameWindowConstructionParams()))
            {
                try
                {
                    DesktopState.BrowserHandle = window.Handle;
                    DesktopState.ConsoleHandle = ConsoleHandle;

                    foreach (var scheme in config.Schemes)
                    {
                        CefRuntime.RegisterSchemeHandlerFactory(scheme.Scheme, scheme.Domain,
                                                                new CefProxySchemeHandlerFactory(scheme));
                        if (scheme.AllowCors && scheme.Domain != null)
                        {
                            CefRuntime.AddCrossOriginWhitelistEntry(config.StartUrl, scheme.TargetScheme ?? scheme.Scheme,
                                                                    scheme.Domain, true);
                        }
                    }

                    foreach (var schemeFactory in config.SchemeFactories)
                    {
                        CefRuntime.RegisterSchemeHandlerFactory(schemeFactory.Scheme, schemeFactory.Domain,
                                                                schemeFactory.Factory);
                        if (schemeFactory.AddCrossOriginWhitelistEntry)
                        {
                            CefRuntime.AddCrossOriginWhitelistEntry(config.StartUrl, schemeFactory.Scheme,
                                                                    schemeFactory.Domain, true);
                        }
                    }

                    // if (config.Verbose)
                    // {
                    //     Console.WriteLine(
                    //         @$"GetScreenResolution: {res.Width}x{res.Height}, scale:{ScaleFactor}, {(int) (ScaleFactor * res.Width)}x{(int) (ScaleFactor * res.Width)}");
                    //     var rect = Instance.GetClientRectangle(window.Handle);
                    //     Console.WriteLine(
                    //         @$"GetClientRectangle:  [{rect.Top},{rect.Left}] [{rect.Bottom},{rect.Right}], scale: [{(int) (rect.Bottom * ScaleFactor)},{(int) (rect.Right * ScaleFactor)}]");
                    // }

                    if (config.CenterToScreen)
                    {
                        window.CenterToScreen();
                    }
                    else if (config.X != null || config.Y != null)
                    {
                        window.SetPosition(config.X.GetValueOrDefault(), config.Y.GetValueOrDefault());
                    }
                    if (config.Kiosk || config.FullScreen)
                    {
                        Instance.SetWindowFullScreen(window.Handle);
                    }
                    else
                    {
                        window.SetSize(config.Width, config.Height - 1); //force redraw in BrowserCreated
                    }

                    window.Browser.BrowserCreated += (sender, args) => {
                        var cef = (CefGlueBrowser)sender;
                        if (!cef.Config.Kiosk)
                        {
                            window.SetSize(config.Width, config.Height); //trigger refresh to sync browser frame with window
                            if (config.CenterToScreen)
                            {
                                window.CenterToScreen();
                            }

                            if (config.FullScreen)
                            {
                                User32.ShowWindow(window.Handle, User32.WindowShowStyle.SW_MAXIMIZE);
                            }
                        }
                        else
                        {
                            EnterKioskMode();
                            cef.BrowserWindowHandle.ShowScrollBar(NativeWin.SB_BOTH, false);
                        }
                    };

                    window.Show();

                    return(new EventLoop().Run(window));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
        }
Exemple #22
0
        internal static void InitializeCef()
        {
            if (!CefUtil.DISABLE_CEF)
            {
                var t = new Thread((ThreadStart) delegate
                {
                    try
                    {
                        //LogManager.CefLog("--> InitilizeCef: Start");
                        CefRuntime.Load(Main.GTANInstallDir + "\\cef");
                        //LogManager.CefLog("-> InitilizeCef: 1");

                        var args = new[]
                        {
                            "--off-screen-rendering-enabled",
                            "--transparent-painting-enabled",
                            "--disable-gpu",
                            "--disable-gpu-compositing",
                            "--disable-gpu-vsync",
                            "--enable-begin-frame-scheduling",
                            "--disable-d3d11",
                        };

                        var cefMainArgs = new CefMainArgs(args);
                        var cefApp      = new MainCefApp();

                        if (CefRuntime.ExecuteProcess(cefMainArgs, cefApp, IntPtr.Zero) != -1)
                        {
                            LogManager.CefLog("CefRuntime could not execute the secondary process.");
                        }

                        //LogManager.CefLog("-> InitilizeCef: 2");
                        var cefSettings = new CefSettings()
                        {
                            SingleProcess              = true,
                            MultiThreadedMessageLoop   = true,
                            WindowlessRenderingEnabled = true,
                            BackgroundColor            = new CefColor(0, 0, 0, 0),
                            CachePath               = Main.GTANInstallDir + "\\cef",
                            ResourcesDirPath        = Main.GTANInstallDir + "\\cef",
                            LocalesDirPath          = Main.GTANInstallDir + "\\cef\\locales",
                            BrowserSubprocessPath   = Main.GTANInstallDir + "\\cef",
                            IgnoreCertificateErrors = true,
                        };
                        if (Main.PlayerSettings.CEFDevtool)
                        {
                            cefSettings.RemoteDebuggingPort = 9222;
                        }

                        CefRuntime.Initialize(cefMainArgs, cefSettings, cefApp, IntPtr.Zero);
                        //LogManager.CefLog("-> InitilizeCef: 3");

                        CefRuntime.RegisterSchemeHandlerFactory("http", null, new SecureSchemeFactory());
                        CefRuntime.RegisterSchemeHandlerFactory("https", null, new SecureSchemeFactory());
                        CefRuntime.RegisterSchemeHandlerFactory("ftp", null, new SecureSchemeFactory());
                        CefRuntime.RegisterSchemeHandlerFactory("sftp", null, new SecureSchemeFactory());
                        //LogManager.CefLog("--> InitilizeCef: End");
                    }
                    catch (Exception ex)
                    {
                        LogManager.CefLog(ex, "cef initialization");
                    }
                });

                t.SetApartmentState(ApartmentState.STA);
                t.Start();
            }
        }
Exemple #23
0
 public override void Create(IntPtr hostHandle, IntPtr winXID)
 {
     CefRuntime.RegisterSchemeHandlerFactory("reko", "", new RekoSchemeHandlerFactory());
     base.Create(hostHandle, winXID);
 }
        public int Initialize()
        {
            if (initialized)
            {
                if (!created)
                {
                    CreateBrowser();
                }
                return(0);
            }
            CefRuntime.Load();
            var settings = new CefSettings();

            settings.MultiThreadedMessageLoop    = CefRuntime.Platform == CefRuntimePlatform.Windows;
            settings.ReleaseDCheckEnabled        = true;
            settings.SingleProcess               = true;
            settings.PersistSessionCookies       = true;
            settings.CommandLineArgsDisabled     = false;
            settings.ContextSafetyImplementation = CefContextSafetyImplementation.SafeDefault;
            settings.IgnoreCertificateErrors     = true;
            settings.ResourcesDirPath            = "/res";
            settings.PackLoadingDisabled         = false;
            settings.LogSeverity         = CefLogSeverity.Default;
            settings.LogFile             = "cef.log";
            settings.ResourcesDirPath    = System.IO.Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetEntryAssembly().CodeBase).LocalPath);
            settings.RemoteDebuggingPort = 9000;
            settings.UserAgent           = browserSettings.UserAgent;
            settings.Locale         = browserSettings.Locale;
            settings.LocalesDirPath = browserSettings.LocaleDirPath;
            settings.CachePath      = browserSettings.CachePath;

            var args = new string[] { };
            var argv = args;

            if (CefRuntime.Platform != CefRuntimePlatform.Windows)
            {
                argv = new string[args.Length + 1];
                Array.Copy(args, 0, argv, 1, args.Length);
                argv[0] = "-";
            }

            var mainArgs = new CefMainArgs(argv);

            Global.app = new ClientApp();
            Global.app.SetBrowserControl(Global.instance);
            var exitCode = CefRuntime.ExecuteProcess(mainArgs, Global.app);

            Console.WriteLine("CefRuntime.ExecuteProcess() returns {0}", exitCode);
            if (exitCode != -1)
            {
                return(exitCode);
            }

            foreach (var arg in args)
            {
                if (arg.StartsWith("--type="))
                {
                    return(-2);
                }
            }
            CefRuntime.Initialize(mainArgs, settings, Global.app);
            CefRuntime.RegisterSchemeHandlerFactory("http", DumpRequestDomain, new AppSchemeHandlerFactory());
            bool b = CefRuntime.AddCrossOriginWhitelistEntry("http://localhost", "http", "", true);

            CreateBrowser();
            initialized = true;
            return(0);
        }
Exemple #25
0
        internal int Initialize()
        {
            var args = Environment.GetCommandLineArgs();


            if (ProcessType == CefProcessType.Browser)
            {
                var currentProcess = Process.GetCurrentProcess();



                ApplicationConfiguration.UseExtensions[(int)ExtensionExecutePosition.MainProcessStartup]?.Invoke(this, ApplicationProperties);
            }

            CefRuntime.Load(ChromiumEnvironment.LibCefDir);

            IsRuntimeInitialized = true;

            if (ProcessType == CefProcessType.Browser)
            {
                var info = $@"
Welcome to NanUI/0.8 Dev ({WinFormium.PlatformArchitecture}); Chromium/{CefRuntime.ChromeVersion}; WinFormium/{Assembly.GetExecutingAssembly().GetName().Version};
Copyrights (C) 2015-{DateTime.Now.Year} NetDimension Studio all rights reserved. Powered by Xuanchen Lin. 
{NanUI.Properties.Resources.ASCII_NanUI_Logo}
This project is under LGPL-3.0 License.
https://github.com/NetDimension/NanUI/blob/master/LICENCE
";

                Logger.Info(info);
            }


            if (!ChromiumEnvironment.ForceHighDpiSupportDisabled)
            {
                CefRuntime.EnableHighDpiSupport();
            }

            ChromiumEnvironment.CefBrowserSettingConfigurations?.Invoke(WinFormium.DefaultBrowserSettings);

            ApplicationConfiguration.UseExtensions[(int)ExtensionExecutePosition.SubProcessStartup]?.Invoke(this, ApplicationProperties);

            var cefMainArgs = new CefMainArgs(args);

            var app = new WinFormiumApp();

            var exitCode = CefRuntime.ExecuteProcess(cefMainArgs, app, IntPtr.Zero);

            Logger.Info(string.Format("CefRuntime.ExecuteProcess() returns {0}", exitCode));



            if (exitCode != -1)
            {
                return(exitCode);
            }

            foreach (var arg in args)
            {
                if (arg.StartsWith("--type="))
                {
                    return(-2);
                }
            }

            RegisterCustomResourceHandler(new ResourceHandler.InternalResource.InternalSchemeConfiguration());



            var settings = new CefSettings
            {
                LogSeverity        = CefLogSeverity.Warning,
                ResourcesDirPath   = ChromiumEnvironment.LibCefResourceDir,
                LocalesDirPath     = ChromiumEnvironment.LibCefLocaleDir,
                Locale             = Thread.CurrentThread.CurrentCulture.ToString(),
                AcceptLanguageList = Thread.CurrentThread.CurrentCulture.ToString(),
                JavaScriptFlags    = "--expose-gc",
                CachePath          = WinFormium.DefaultAppDataDirectory,
            };

            settings.LogFile = Path.Combine(settings.CachePath, "debug.log");

            ChromiumEnvironment.SettingConfigurations?.Invoke(settings);

            settings.MultiThreadedMessageLoop = true;

            settings.NoSandbox = true;

            if (!string.IsNullOrEmpty(ChromiumEnvironment.SubprocessPath))
            {
                settings.BrowserSubprocessPath = ChromiumEnvironment.SubprocessPath;
            }


            CefRuntime.Initialize(new CefMainArgs(args), settings, app, IntPtr.Zero);

            ApplicationConfiguration.UseExtensions[(int)ExtensionExecutePosition.Initialized]?.Invoke(this, ApplicationProperties);

            foreach (var config in CustomResourceHandlerConfigurations)
            {
                config.OnResourceHandlerRegister();

                if (!CefRuntime.RegisterSchemeHandlerFactory(config.Scheme, config.DomainName, config))
                {
                    throw new InvalidOperationException("ResouceHandler is fail to be registered");
                }
            }

            var context = GetAppContext();

            if (context == null)
            {
                context = ApplicationConfiguration.UseApplicationContext?.Invoke();

                if (context != null)
                {
                    context.ThreadExit += (_, args) =>
                    {
                        Application.Exit();
                    };
                }
            }

            if (context != null)
            {
                Application.Run(context);

                return(0);
            }


            Environment.Exit(-1);

            return(-1);
        }
        public void Start()
        {
            ManualResetEventSlim contextInitializedEvent =
                new ManualResetEventSlim();

            dispatcher.PostTask(new Action(() =>
            {
                CefRuntime.Load();
                CefMainArgs cefMainArgs         = new CefMainArgs(IntPtr.Zero, new String[0]);
                BrowserRuntimeSettings settings = BrowserSettings.Instance.RuntimeSettings;

                isMultiThreadedMessageLoop = settings.MultiThreadedMessageLoop;
                isSingleProcess            = BrowserSettings.Instance.RuntimeSettings.SingleProcess;

                string browserSubprocessPath = Path.Combine(AssemblyDirectory,
                                                            "CLRBrowserSourcePlugin", "CLRBrowserSourceClient.exe");

                CefSettings cefSettings = new CefSettings
                {
                    BrowserSubprocessPath   = browserSubprocessPath,
                    CachePath               = settings.CachePath,
                    CommandLineArgsDisabled = settings.CommandLineArgsDisabled,
                    IgnoreCertificateErrors = settings.IgnoreCertificateErrors,
                    JavaScriptFlags         = settings.JavaScriptFlags,
                    Locale                     = settings.Locale,
                    LocalesDirPath             = settings.LocalesDirPath,
                    LogFile                    = settings.LogFile,
                    LogSeverity                = settings.LogSeverity,
                    MultiThreadedMessageLoop   = settings.MultiThreadedMessageLoop,
                    NoSandbox                  = true,
                    PersistSessionCookies      = settings.PersistSessionCookies,
                    ProductVersion             = settings.ProductVersion,
                    RemoteDebuggingPort        = settings.RemoteDebuggingPort,
                    ResourcesDirPath           = settings.ResourcesDirPath,
                    SingleProcess              = false,
                    UncaughtExceptionStackSize = settings.UncaughtExceptionStackSize,
                    WindowlessRenderingEnabled = true
                };

                string[] commandLineArgs = settings.CommandLineArgsDisabled ?
                                           new String[0] : settings.CommandLineArguments;

                BrowserApp browserApp = new BrowserApp(
                    commandLineArgs, contextInitializedEvent);

                try
                {
                    CefRuntime.Initialize(cefMainArgs, cefSettings, browserApp, IntPtr.Zero);
                }
                catch (InvalidOperationException e)
                {
                    API.Instance.Log("Failed to initialize cef runtime");
                    contextInitializedEvent.Set();
                }

                CefRuntime.RegisterSchemeHandlerFactory("local", null, new AssetSchemeHandlerFactory());
                CefRuntime.RegisterSchemeHandlerFactory("http", "absolute", new AssetSchemeHandlerFactory());

                if (!settings.MultiThreadedMessageLoop)
                {
                    CefRuntime.RunMessageLoop();
                }
            }));

            contextInitializedEvent.Wait();
        }
Exemple #27
0
        private static int Main(string[] args)
        {
            PublicClass.currDirectiory = Environment.CurrentDirectory.ToString(); // PublicClass.currDirectiory = System.Windows.Forms.Application.StartupPath;
            new ProcessHook().InitHook();
            try
            {
                CefRuntime.Load();
            }
            catch (DllNotFoundException ex)
            {
                MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(1);
            }
            catch (CefRuntimeException ex)
            {
                MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(2);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(3);
            }

            var mainArgs = new CefMainArgs(args);
            var app      = new DemoApp();

            var exitCode = CefRuntime.ExecuteProcess(mainArgs, app, IntPtr.Zero);

            if (exitCode != -1)
            {
                return(exitCode);
            }

            var codeBase    = Assembly.GetExecutingAssembly().CodeBase;
            var localFolder = Path.GetDirectoryName(new Uri(codeBase).LocalPath);
            var settings    = new CefSettings
            {
                //BrowserSubprocessPath = browserProcessPath,
                //SingleProcess = false,
                //WindowlessRenderingEnabled = true,
                MultiThreadedMessageLoop = true,
                LogSeverity = CefLogSeverity.Disable,
                //LogFile = "CefGlue.log",
                Locale                  = "zh-CN",
                JavaScriptFlags         = "js-flags",
                CommandLineArgsDisabled = false,
                IgnoreCertificateErrors = true,
                CachePath               = GetAppDir("Cache"),
                UserAgent               = CefConstHelper.UserAgent,
                //NoSandbox = true,

                //AcceptLanguageList = "zh-CN",
                //PersistSessionCookies = true,
            };


            CefRuntime.RegisterSchemeHandlerFactory(CefConstHelper.Branding, CefConstHelper.Branding, new SchemeHandlerFactory());
            CefRuntime.Initialize(mainArgs, settings, app, IntPtr.Zero);
            Application.EnableVisualStyles();
            CefRuntime.EnableHighDpiSupport();
            Application.SetCompatibleTextRenderingDefault(false);

            if (!settings.MultiThreadedMessageLoop)
            {
                Application.Idle += (sender, e) => { CefRuntime.DoMessageLoopWork(); };
            }

            if (args.Length > 0)
            {
                Application.Run(new MainForm(args[0].ToString()));

                //MessageBox.Show(PublicClass.StartUrl);
            }
            else
            {
                Application.Run(new MainForm(""));
            }


            CefRuntime.Shutdown();

            try
            {
                //if (Directory.Exists(GetAppDir("Cache")))
                //    Directory.Delete(GetAppDir("Cache"), true);
            }
            catch
            { }
            return(0);
        }
Exemple #28
0
        private static int Main(string[] args1)
        {
            //自定义初始化系统配置
            InitAllinOne();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            MainForm.taskRunner   = GlobalUI.taskRunner;
            GlobalVar.AccountList = HaoziHelper.importAccounts();
            //导入账号信息

            //每个账号建立一个cache
            string zfbEmail = "";

            zfbEmail = GlobalVar.AccountList.Count == 0 ? "downloadAccount" : GlobalVar.AccountList[0].zfbEmail;
            string MyCachePath = Application.StartupPath + "\\cache\\{0}\\".With(zfbEmail);

            if (!Directory.Exists(MyCachePath))
            {
                Directory.CreateDirectory(MyCachePath);
            }

            //每个账号建立一个个性化信息配置文件
            string zfbEmailConfig = MyCachePath + zfbEmail + ".txt";
            string httpHeadAgent  = FileHelper.RandomReadOneLine("Resources//httpHead.txt").ReplaceNum();

            if (!File.Exists(zfbEmailConfig))
            {
                //  File.Create(zfbEmailConfig); //Directory.CreateDirectory(MyCachePath);
                File.WriteAllText(zfbEmailConfig, httpHeadAgent);
            }
            else
            {
                httpHeadAgent = File.ReadAllLines(zfbEmailConfig)[0];
            }
            GlobalCefGlue.UserAgent = httpHeadAgent;
            LogManager.WriteLog(httpHeadAgent + " " + MyCachePath);

            //
            string[] args = { "" };
            int      main;

            if (cefruntimeLoad(out main))
            {
                return(main);
            }
            var mainArgs = new CefMainArgs(args);
            var app      = new DemoApp();

            var exitCode = CefRuntime.ExecuteProcess(mainArgs, app);

            if (exitCode != -1)
            {
                return(exitCode);
            }

            var settings = new CefSettings {
                // BrowserSubprocessPath = @"D:\fddima\Projects\Xilium\Xilium.CefGlue\CefGlue.Demo\bin\Release\Xilium.CefGlue.Demo.exe",
                SingleProcess = false,
                LogSeverity   = CefLogSeverity.Disable,
                LogFile       = "CefGlue.log",
                //设置缓存地址
                CachePath           = MyCachePath,// Application.StartupPath + "\\cache\\{0}\\".With(zfbEmail),
                RemoteDebuggingPort = 20480,
                //  UserAgent = httpHeadAgent//FileHelper.RandomReadOneLine("Resources//httpHead.txt").ReplaceNum()
            };

            if (ConfigHelper.GetBoolValue("UseUserAgent"))
            {
                settings.UserAgent = httpHeadAgent;
            }
            settings.UserAgent = httpHeadAgent;

            //   settings.MultiThreadedMessageLoop = CefRuntime.Platform == CefRuntimePlatform.Windows;
            settings.MultiThreadedMessageLoop = bool.Parse(ConfigHelper.GetValue("MultiThreadedMessageLoop"));
            ;

            CefRuntime.Initialize(mainArgs, settings, app);
            //注册  register custom scheme handler
            //
            CefRuntime.RegisterSchemeHandlerFactory("http", GlobalVar.Js2CsharpRequestDomain, new Js2CsharpSchemeHandlerFactory());
            CefRuntime.AddCrossOriginWhitelistEntry(
                "http://trade.taobao.com", "http", "https://tbapi.alipay.com", true);
            CefRuntime.AddCrossOriginWhitelistEntry(
                "http://trade.taobao.com", "https", "https://tbapi.alipay.com", true);

            if (!settings.MultiThreadedMessageLoop)
            {
                Application.Idle += (sender, e) => { CefRuntime.DoMessageLoopWork(); };
            }

            MainForm mainform;

            //通过配置觉得是否自运行
            if (GlobalVar.autoRun)
            {
                mainform = new MainForm(true);
            }
            else
            {
                mainform = new MainForm();
            }

            Application.Run(mainform);

            CefRuntime.Shutdown();


            return(0);
        }
Exemple #29
0
        /// <summary>
        /// 主RUN函数
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public int Run(string[] args)
        {
            //1.加载运行时
            CefRuntime.Load();
            //2.设置
            var settings = new CefSettings();

            settings.MultiThreadedMessageLoop = CefRuntime.Platform == CefRuntimePlatform.Windows;
            settings.ReleaseDCheckEnabled     = true;
            settings.LogSeverity         = CefLogSeverity.Verbose;
            settings.LogFile             = "cef.log";
            settings.ResourcesDirPath    = System.IO.Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetEntryAssembly().CodeBase).LocalPath);
            settings.RemoteDebuggingPort = 20480;
            //D:\01 project\3 FastQQ\xl\xilium-xilium.cefglue-820e4919a0f1\CefGlue.Client\bin\Debug\cache
            string cacahePath =
                @"D:\01 project\3 FastQQ\xl\xilium-xilium.cefglue-820e4919a0f1\CefGlue.Client\bin\Debug\cache";

            //  string cacahePath2 = Application.StartupPath+"\\cache";
            settings.CachePath = cacahePath;
            // settings.

            var argv = args;

            if (CefRuntime.Platform != CefRuntimePlatform.Windows)
            {
                argv = new string[args.Length + 1];
                Array.Copy(args, 0, argv, 1, args.Length);
                argv[0] = "-";
            }

            var mainArgs = new CefMainArgs(argv);
            var app      = new DemoCefApp();

            var exitCode = CefRuntime.ExecuteProcess(mainArgs, app);

            Console.WriteLine("CefRuntime.ExecuteProcess() returns {0}", exitCode);
            if (exitCode != -1)
            {
                return(exitCode);
            }

            // guard if something wrong
            foreach (var arg in args)
            {
                if (arg.StartsWith("--type="))
                {
                    return(-2);
                }
            }

            CefRuntime.Initialize(mainArgs, settings, app);

            // register custom scheme handler
            CefRuntime.RegisterSchemeHandlerFactory("http", DumpRequestDomain, new DemoAppSchemeHandlerFactory());
            //  CefRuntime.RegisterSchemeHandlerFactory("http", Js2CsharpRequestDomain, new DemoAppSchemeHandlerFactory());
            //AddCrossOriginWhitelistEntry 似乎没有用
            //CefRuntime.AddCrossOriginWhitelistEntry(
            //   "http://trade.taobao.com", "http", "https://tbapi.alipay.com", true);
            //CefRuntime.AddCrossOriginWhitelistEntry(
            //   "http://trade.taobao.com", "https", "https://tbapi.alipay.com", true);
            //CefRuntime.AddCrossOriginWhitelistEntry(
            //  string.Format("{0}", "tbapi.alipay.com"), "https", "", true);
            //alipay.com
            PlatformInitialize();

            var mainMenu = CreateMainMenu();

            _mainView = CreateMainView(mainMenu);
            _mainView.NewTab(HomeUrl);

            PlatformRunMessageLoop();

            _mainView.Dispose();
            _mainView = null;

            CefRuntime.Shutdown();

            PlatformShutdown();
            return(0);
        }
Exemple #30
0
        private static int Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);


            try
            {
                CefRuntime.Load();
            }
            catch (DllNotFoundException ex)
            {
                MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(1);
            }
            catch (CefRuntimeException ex)
            {
                MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(2);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(3);
            }

            //hmm not working
            //Should maybe move to callback in render process vs can modify from browser process this way
            //Array.Resize(ref args, args.Length + 1);
            //args[args.Length - 1] = @"--log-file ""..\logs\LVCef.RenderApp.log""";
            //for (int i = 0; i < args.Length; i++)
            //    Debug.WriteLine("Render args[" + i +"]: " + args[i]);

            var mainArgs = new CefMainArgs(args);
            var exitCode = CefRuntime.ExecuteProcess(mainArgs, null, IntPtr.Zero);

            if (exitCode != -1)
            {
                return(exitCode);
            }

            var settings = new CefSettings
            {
                //Relative path from \cef, make sure to set Working Directory to \cef, see README.md
                //BrowserSubprocessPath = @"..\dotnet\LVCef.RenderApp\bin\Debug\LVCef.RenderApp.exe",
                BrowserSubprocessPath    = @"LVCef.RenderApp.exe",
                SingleProcess            = false,
                MultiThreadedMessageLoop = true,
                LogSeverity = CefLogSeverity.Default,
                //LogFile = @"..\logs\TestControlAppSimple.log",
                LogFile = @"log.log",
            };

            CefRuntime.Initialize(mainArgs, settings, null, IntPtr.Zero);

            string DumpRequestDomain = "test.local";

            // register custom scheme handler
            CefRuntime.RegisterSchemeHandlerFactory("http", DumpRequestDomain, new DemoAppSchemeHandlerFactory());
            // CefRuntime.AddCrossOriginWhitelistEntry("http://localhost", "http", "", true);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (!settings.MultiThreadedMessageLoop)
            {
                Application.Idle += (sender, e) => { CefRuntime.DoMessageLoopWork(); };
            }

            Application.Run(new TestControlAppSimpleForm());

            CefRuntime.Shutdown();
            return(0);
        }