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;
        }
示例#2
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;
                }
            }
        }
        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);
        }
示例#4
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);
        }
示例#5
0
文件: Runtime.cs 项目: maxjove/NanUI
        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);
            CefRuntime.AddCrossOriginWhitelistEntry("*", "http", "*", true);
            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);
        }