Example #1
0
        /// <summary>
        /// This function should be called from the application entry point function (typically Program.Main)
        /// to execute a secondary process e.g. gpu, plugin, renderer, utility
        /// This overload is specifically used for .Net Core. For hosting your own BrowserSubProcess
        /// it's preferable to use the Main method provided by this class.
        /// - Pass in command line args
        /// - To support High DPI Displays you should call  Cef.EnableHighDPISupport before any other processing
        /// or add the relevant entries to your app.manifest
        /// </summary>
        /// <param name="args">command line args</param>
        /// <returns>
        /// If called for the browser process (identified by no "type" command-line value) it will return immediately
        /// with a value of -1. If called for a recognized secondary process it will block until the process should exit
        /// and then return the process exit code.
        /// </returns>
        public static int Main(string[] args)
        {
            var type = CommandLineArgsParser.GetArgumentValue(args, CefSharpArguments.SubProcessTypeArgument);

            if (string.IsNullOrEmpty(type))
            {
                //If --type param missing from command line CEF/Chromium assums
                //this is the main process (as all subprocesses must have a type param).
                //Return -1 to indicate this behaviour.
                return(-1);
            }

            var browserSubprocessDllPath = Path.Combine(Path.GetDirectoryName(typeof(CefSharp.Core.BrowserSettings).Assembly.Location), "CefSharp.BrowserSubprocess.Core.dll");

#if NETCOREAPP
            var browserSubprocessDll = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(browserSubprocessDllPath);
#else
            var browserSubprocessDll = System.Reflection.Assembly.LoadFrom(browserSubprocessDllPath);
#endif
            var browserSubprocessExecutableType = browserSubprocessDll.GetType("CefSharp.BrowserSubprocess.BrowserSubprocessExecutable");
            var browserSubprocessExecutable     = Activator.CreateInstance(browserSubprocessExecutableType);

            var mainMethod = browserSubprocessExecutableType.GetMethod("MainSelfHost", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
            var argCount   = mainMethod.GetParameters();

            var methodArgs = new object[] { args };

            var exitCode = mainMethod.Invoke(null, methodArgs);

            return((int)exitCode);
        }
Example #2
0
        public static async Task Main(string[] args)
        {
            IList <string> positionalArgs;
            IDictionary <string, IList <string> > opts;

            try
            {
                (positionalArgs, opts) = CommandLineArgsParser.Parse(args, new (string?, string, bool)[]
Example #3
0
 public LaunchHandler(
     CommandLineArgsParser parser,
     LaunchOptionsVisitor optionsVisitor,
     OutputPresenter outputPresenter)
 {
     _parser          = parser;
     _optionsVisitor  = optionsVisitor;
     _outputPresenter = outputPresenter;
 }
Example #4
0
        static void Main(string[] args)
        {
            try
            {
                var arguments = new Arguments();
                CommandLineArgsParser.Parse(args, arguments, autoHelp: true);

                MainImpl(arguments);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Exception raised: {0}", ex.ToString());
            }
        }
        public void TestValidString()
        {
            CommandLineArgs args = CommandLineArgsParser.ReadCefArguments("--aaa --bbb --first-value=123 --SECOND-VALUE=\"a b c d e\" --ccc");

            // cef has no flags, flag arguments have a value of 1
            // the processing removes all dashes in front of each key

            Assert.AreEqual(5, args.Count);
            Assert.IsTrue(args.HasValue("aaa"));
            Assert.IsTrue(args.HasValue("bbb"));
            Assert.IsTrue(args.HasValue("ccc"));
            Assert.IsTrue(args.HasValue("first-value"));
            Assert.IsTrue(args.HasValue("second-value"));
            Assert.AreEqual("1", args.GetValue("aaa", string.Empty));
            Assert.AreEqual("1", args.GetValue("bbb", string.Empty));
            Assert.AreEqual("1", args.GetValue("ccc", string.Empty));
            Assert.AreEqual("123", args.GetValue("first-value", string.Empty));
            Assert.AreEqual("a b c d e", args.GetValue("second-value", string.Empty));
        }
        private void btnApply_Click(object sender, EventArgs e)
        {
            string prevArgs = Program.UserConfig.CustomCefArgs;

            if (CefArgs == prevArgs)
            {
                DialogResult = DialogResult.Cancel;
                Close();
                return;
            }

            int    count  = CommandLineArgsParser.ReadCefArguments(CefArgs).Count;
            string prompt = count == 0 && !string.IsNullOrWhiteSpace(prevArgs) ? "All arguments will be removed from the settings. Continue?" : count + (count == 1 ? " argument" : " arguments") + " will be added to the settings. Continue?";

            if (MessageBox.Show(prompt, "Confirm CEF Arguments", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                DialogResult = DialogResult.OK;
                Close();
            }
        }
 protected override void Arrange()
 {
     args   = new[] { "command", "--option1", "32", "--option2", "desc" };
     parser = new CommandLineArgsParser("--", new[] { '=', ':' }, 0);
 }
Example #8
0
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            WindowRestoreMessage = NativeMethods.RegisterWindowMessage("TweetDuckRestore");

            if (!WindowsUtils.CheckFolderWritePermission(StoragePath))
            {
                MessageBox.Show(BrandName + " does not have write permissions to the storage folder: " + StoragePath, "Permission Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            Reporter = new Reporter(ErrorLogFilePath);
            Reporter.SetupUnhandledExceptionHandler(BrandName + " Has Failed :(");

            if (Arguments.HasFlag(Arguments.ArgRestart))
            {
                for (int attempt = 0; attempt < 21; attempt++)
                {
                    LockManager.Result lockResult = LockManager.Lock();

                    if (lockResult == LockManager.Result.Success)
                    {
                        break;
                    }
                    else if (lockResult == LockManager.Result.Fail)
                    {
                        MessageBox.Show("An unknown error occurred accessing the data folder. Please, make sure " + BrandName + " is not already running. If the problem persists, try restarting your system.", BrandName + " Has Failed :(", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else if (attempt == 20)
                    {
                        using (FormMessage form = new FormMessage(BrandName + " Cannot Restart", BrandName + " is taking too long to close.", MessageBoxIcon.Warning)){
                            form.CancelButton  = form.AddButton("Exit");
                            form.ActiveControl = form.AddButton("Retry", DialogResult.Retry);

                            if (form.ShowDialog() == DialogResult.Retry)
                            {
                                attempt /= 2;
                                continue;
                            }

                            return;
                        }
                    }
                    else
                    {
                        Thread.Sleep(500);
                    }
                }
            }
            else
            {
                LockManager.Result lockResult = LockManager.Lock();

                if (lockResult == LockManager.Result.HasProcess)
                {
                    if (LockManager.LockingProcess.MainWindowHandle == IntPtr.Zero)  // restore if the original process is in tray
                    {
                        NativeMethods.SendMessage(NativeMethods.HWND_BROADCAST, WindowRestoreMessage, LockManager.LockingProcess.Id, IntPtr.Zero);

                        if (WindowsUtils.TrySleepUntil(() => {
                            LockManager.LockingProcess.Refresh();
                            return(LockManager.LockingProcess.HasExited || (LockManager.LockingProcess.MainWindowHandle != IntPtr.Zero && LockManager.LockingProcess.Responding));
                        }, 2000, 250))
                        {
                            return; // should trigger on first attempt if succeeded, but wait just in case
                        }
                    }

                    if (MessageBox.Show("Another instance of " + BrandName + " is already running.\r\nDo you want to close it?", BrandName + " is Already Running", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        if (!LockManager.CloseLockingProcess(10000, 5000))
                        {
                            MessageBox.Show("Could not close the other process.", BrandName + " Has Failed :(", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        LockManager.Lock();
                    }
                    else
                    {
                        return;
                    }
                }
                else if (lockResult != LockManager.Result.Success)
                {
                    MessageBox.Show("An unknown error occurred accessing the data folder. Please, make sure " + BrandName + " is not already running. If the problem persists, try restarting your system.", BrandName + " Has Failed :(", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            ReloadConfig();

            if (Arguments.HasFlag(Arguments.ArgImportCookies))
            {
                ExportManager.ImportCookies();
            }

            CefSharpSettings.WcfEnabled = false;

            CefSettings settings = new CefSettings {
                AcceptLanguageList = BrowserUtils.HeaderAcceptLanguage,
                UserAgent          = BrowserUtils.HeaderUserAgent,
                Locale             = Arguments.GetValue(Arguments.ArgLocale, string.Empty),
                CachePath          = StoragePath,
                LogFile            = ConsoleLogFilePath,
                #if !DEBUG
                BrowserSubprocessPath = BrandName + ".Browser.exe",
                LogSeverity           = Arguments.HasFlag(Arguments.ArgLogging) ? LogSeverity.Info : LogSeverity.Disable
                #endif
            };

            CommandLineArgsParser.ReadCefArguments(UserConfig.CustomCefArgs).ToDictionary(settings.CefCommandLineArgs);

            if (!HardwareAcceleration.IsEnabled)
            {
                settings.CefCommandLineArgs["disable-gpu"]       = "1";
                settings.CefCommandLineArgs["disable-gpu-vsync"] = "1";
            }

            settings.CefCommandLineArgs["disable-extensions"]        = "1";
            settings.CefCommandLineArgs["disable-plugins-discovery"] = "1";
            settings.CefCommandLineArgs["enable-system-flash"]       = "0";

            Cef.Initialize(settings, false, new BrowserProcessHandler());

            Application.ApplicationExit += (sender, args) => ExitCleanup();

            PluginManager plugins = new PluginManager(PluginPath, UserConfig.Plugins);

            plugins.Reloaded += plugins_Reloaded;
            plugins.Executed += plugins_Executed;
            plugins.Reload();

            FormBrowser mainForm = new FormBrowser(plugins, new UpdaterSettings {
                AllowPreReleases = Arguments.HasFlag(Arguments.ArgDebugUpdates),
                DismissedUpdate  = UserConfig.DismissedUpdate
            });

            Application.Run(mainForm);

            if (mainForm.UpdateInstallerPath != null)
            {
                ExitCleanup();

                // ProgramPath has a trailing backslash
                string updaterArgs = "/SP- /SILENT /CLOSEAPPLICATIONS /UPDATEPATH=\"" + ProgramPath + "\" /RUNARGS=\"" + Arguments.GetCurrentClean().ToString().Replace("\"", "^\"") + "\"" + (IsPortable ? " /PORTABLE=1" : "");
                bool   runElevated = !IsPortable || !WindowsUtils.CheckFolderWritePermission(ProgramPath);

                WindowsUtils.StartProcess(mainForm.UpdateInstallerPath, updaterArgs, runElevated);
                Application.Exit();
            }
        }
 public void TestEmptyString()
 {
     Assert.AreEqual(0, CommandLineArgsParser.ReadCefArguments("").Count);
     Assert.AreEqual(0, CommandLineArgsParser.ReadCefArguments("     ").Count);
 }
 protected override void Arrange()
 {
     args   = new string[0];
     parser = new CommandLineArgsParser("--", new[] { '=', ':' }, 0);
 }
Example #11
0
 private static void ExecuteFromCommandLine(string[] args)
 {
     CommandLineArgsParser.GetWorkItems(args).ForEach(ExecuteSingleWorkItem);
 }