public static void Init(bool noHardwareMode, IUserSettingService userSettingService)
        {
            Thread thread = new Thread(() =>
            {
                if (userSettingService.GetUserSetting <bool>(UserSettingConstants.ForceDisableHardwareSupport))
                {
                    noHardware = true;
                }
                else
                {
                    noHardware = noHardwareMode;
                }

                HandBrakeUtils.RegisterLogger();
                HandBrakeUtils.EnsureGlobalInit(noHardware);
            });

            thread.Start();
            if (!thread.Join(8000))
            {
                // Something is likely handing in a graphics driver.  Force disable this feature so we don't probe the hardware next time around.
                userSettingService.SetUserSetting(UserSettingConstants.ForceDisableHardwareSupport, true);
                throw new GeneralApplicationException(Resources.Startup_UnableToStart, Resources.Startup_UnableToStartInfo);
            }
        }
        /// <summary>
        /// Play the Encoded file
        /// </summary>
        private void PlayFile()
        {
            // Launch VLC and Play video.
            if (this.CurrentlyPlaying != string.Empty)
            {
                if (File.Exists(this.CurrentlyPlaying))
                {
                    string args = "\"" + this.CurrentlyPlaying + "\"";

                    if (this.UseSystemDefaultPlayer)
                    {
                        Process.Start(args);
                    }
                    else
                    {
                        if (!File.Exists(userSettingService.GetUserSetting <string>(UserSettingConstants.VLCPath)))
                        {
                            // Attempt to find VLC if it doesn't exist in the default set location.
                            string vlcPath;

                            if (8 == IntPtr.Size || (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
                            {
                                vlcPath = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
                            }
                            else
                            {
                                vlcPath = Environment.GetEnvironmentVariable("ProgramFiles");
                            }

                            if (!string.IsNullOrEmpty(vlcPath))
                            {
                                vlcPath = Path.Combine(vlcPath, "VideoLAN\\VLC\\vlc.exe");
                            }

                            if (File.Exists(vlcPath))
                            {
                                userSettingService.SetUserSetting(UserSettingConstants.VLCPath, vlcPath);
                            }
                            else
                            {
                                this.errorService.ShowMessageBox(Resources.StaticPreviewViewModel_UnableToFindVLC,
                                                                 Resources.Error, MessageBoxButton.OK, MessageBoxImage.Warning);
                            }
                        }

                        if (File.Exists(userSettingService.GetUserSetting <string>(UserSettingConstants.VLCPath)))
                        {
                            ProcessStartInfo vlc = new ProcessStartInfo(userSettingService.GetUserSetting <string>(UserSettingConstants.VLCPath), args);
                            Process.Start(vlc);
                        }
                    }
                }
                else
                {
                    this.errorService.ShowMessageBox(Resources.StaticPreviewViewModel_UnableToPlayFile,
                                                     Resources.Error, MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }
Beispiel #3
0
        private static void CheckForUpdateCheckPermission(IUserSettingService userSettingService)
        {
            if (Portable.IsPortable() && !Portable.IsUpdateCheckEnabled())
            {
                return; // If Portable Mode has disabled it, don't bother the user. Just accept it's disabled.
            }

            MessageBoxResult result = MessageBox.Show(HandBrakeWPF.Properties.Resources.FirstRun_EnableUpdateCheck, HandBrakeWPF.Properties.Resources.FirstRun_EnableUpdateCheckHeader, MessageBoxButton.YesNo, MessageBoxImage.Question);

            // Be explicit setting it to true/false as it may have been turned on during first-run.
            userSettingService.SetUserSetting(UserSettingConstants.UpdateStatus, result == MessageBoxResult.Yes);
        }
Beispiel #4
0
        /// <summary>
        /// Check for Updates.
        /// </summary>
        public static void CheckForUpdates()
        {
            IUserSettingService userSettingService = IoC.Get <IUserSettingService>();

            userSettingService.SetUserSetting(UserSettingConstants.LastUpdateCheckDate, DateTime.Now);
            string url = userSettingService.GetUserSetting <string>(ASUserSettingConstants.HandBrakePlatform).Contains("x86_64")
                                                  ? userSettingService.GetUserSetting <string>(UserSettingConstants.Appcast_x64)
                                                  : userSettingService.GetUserSetting <string>(UserSettingConstants.Appcast_i686);

            UpdateService.BeginCheckForUpdates(UpdateCheckDoneMenu, false,
                                               url, userSettingService.GetUserSetting <int>(ASUserSettingConstants.HandBrakeBuild),
                                               userSettingService.GetUserSetting <int>(UserSettingConstants.Skipversion));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EncodeServiceWrapper"/> class.
        /// </summary>
        /// <param name="userSettingService">
        /// The user setting service.
        /// </param>
        public EncodeServiceWrapper(IUserSettingService userSettingService)
        {
            var useLibHb = userSettingService.GetUserSetting<bool>(UserSettingConstants.EnableLibHb);
            var useProcessIsolation =
                userSettingService.GetUserSetting<bool>(UserSettingConstants.EnableProcessIsolation);
            var port = userSettingService.GetUserSetting<string>(UserSettingConstants.ServerPort);

            if (useLibHb)
            {
                try
                {
                    if (useProcessIsolation)
                    {
                        this.encodeService = new IsolatedEncodeService(port);
                    }
                    else
                    {
                        if (ScanServiceWrapper.HandbrakeInstance == null)
                        {
                            ScanServiceWrapper.HandbrakeInstance = new HandBrakeInstance();
                        }

                        this.encodeService = new LibEncode(userSettingService, ScanServiceWrapper.HandbrakeInstance);
                    }
                }
                catch (Exception exc)
                {
                    // Try to recover from errors.
                    userSettingService.SetUserSetting(UserSettingConstants.EnableLibHb, false);
                    throw new GeneralApplicationException(
                        "Unable to initialise LibHB or Background worker service",
                        "Falling back to using HandBrakeCLI.exe. Setting has been reset",
                        exc);
                }
            }
            else
            {
                this.encodeService = new Encode(userSettingService);
            }

            this.encodeService.EncodeCompleted += this.EncodeServiceEncodeCompleted;
            this.encodeService.EncodeStarted += this.EncodeServiceEncodeStarted;
            this.encodeService.EncodeStatusChanged += this.EncodeServiceEncodeStatusChanged;
        }
Beispiel #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EncodeServiceWrapper"/> class.
        /// </summary>
        /// <param name="userSettingService">
        /// The user setting service.
        /// </param>
        public EncodeServiceWrapper(IUserSettingService userSettingService)
        {
            var useLibHb            = userSettingService.GetUserSetting <bool>(UserSettingConstants.EnableLibHb);
            var useProcessIsolation =
                userSettingService.GetUserSetting <bool>(UserSettingConstants.EnableProcessIsolation);
            var port = userSettingService.GetUserSetting <string>(UserSettingConstants.ServerPort);

            if (useLibHb)
            {
                try
                {
                    if (useProcessIsolation)
                    {
                        this.encodeService = new IsolatedEncodeService(port);
                    }
                    else
                    {
                        if (ScanServiceWrapper.HandbrakeInstance == null)
                        {
                            ScanServiceWrapper.HandbrakeInstance = new HandBrakeInstance();
                        }

                        this.encodeService = new LibEncode(userSettingService, ScanServiceWrapper.HandbrakeInstance);
                    }
                }
                catch (Exception exc)
                {
                    // Try to recover from errors.
                    userSettingService.SetUserSetting(UserSettingConstants.EnableLibHb, false);
                    throw new GeneralApplicationException(
                              "Unable to initialise LibHB or Background worker service",
                              "Falling back to using HandBrakeCLI.exe. Setting has been reset",
                              exc);
                }
            }
            else
            {
                this.encodeService = new Encode(userSettingService);
            }

            this.encodeService.EncodeCompleted     += this.EncodeServiceEncodeCompleted;
            this.encodeService.EncodeStarted       += this.EncodeServiceEncodeStarted;
            this.encodeService.EncodeStatusChanged += this.EncodeServiceEncodeStatusChanged;
        }
Beispiel #7
0
        /// <summary>
        /// Perform a startup update check. Abiding by user settings.
        /// </summary>
        public static void PerformStartupUpdateCheck()
        {
            // Make sure it's running on the calling thread
            IUserSettingService userSettingService = IoC.Get <IUserSettingService>();

            if (userSettingService.GetUserSetting <bool>(UserSettingConstants.UpdateStatus))
            {
                if (DateTime.Now.Subtract(userSettingService.GetUserSetting <DateTime>(UserSettingConstants.LastUpdateCheckDate)).TotalDays
                    > userSettingService.GetUserSetting <int>(UserSettingConstants.DaysBetweenUpdateCheck))
                {
                    userSettingService.SetUserSetting(UserSettingConstants.LastUpdateCheckDate, DateTime.Now);
                    string url = userSettingService.GetUserSetting <string>(ASUserSettingConstants.HandBrakePlatform).Contains("x86_64")
                                                          ? userSettingService.GetUserSetting <string>(UserSettingConstants.Appcast_x64)
                                                          : userSettingService.GetUserSetting <string>(UserSettingConstants.Appcast_i686);
                    UpdateService.BeginCheckForUpdates(UpdateCheckDone, false,
                                                       url, userSettingService.GetUserSetting <int>(ASUserSettingConstants.HandBrakeBuild),
                                                       userSettingService.GetUserSetting <int>(UserSettingConstants.Skipversion));
                }
            }
        }
Beispiel #8
0
 private void drp_completeOption_SelectedIndexChanged(object sender, EventArgs e)
 {
     userSettingService.SetUserSetting(UserSettingConstants.WhenCompleteAction, drp_completeOption.Text);
 }
        /// <summary>
        /// Save the settings selected
        /// </summary>
        private void Save()
        {
            /* General */
            this.userSettingService.SetUserSetting(UserSettingConstants.UpdateStatus, this.CheckForUpdates);
            this.userSettingService.SetUserSetting(UserSettingConstants.DaysBetweenUpdateCheck, this.CheckForUpdatesFrequency);
            this.userSettingService.SetUserSetting(UserSettingConstants.WhenCompleteAction, this.WhenDone);
            this.userSettingService.SetUserSetting(UserSettingConstants.SendFileTo, this.SendFileToPath);
            this.userSettingService.SetUserSetting(UserSettingConstants.SendFile, this.SendFileAfterEncode);
            this.userSettingService.SetUserSetting(UserSettingConstants.SendFileToArgs, this.Arguments);
            this.userSettingService.SetUserSetting(UserSettingConstants.ResetWhenDoneAction, this.ResetWhenDoneAction);
            this.userSettingService.SetUserSetting(UserSettingConstants.ShowQueueInline, this.ShowQueueInline);

            /* Output Files */
            this.userSettingService.SetUserSetting(UserSettingConstants.AutoNaming, this.AutomaticallyNameFiles);
            this.userSettingService.SetUserSetting(UserSettingConstants.AutoNameFormat, this.AutonameFormat);
            this.userSettingService.SetUserSetting(UserSettingConstants.AutoNamePath, this.AutoNameDefaultPath);
            this.userSettingService.SetUserSetting(UserSettingConstants.UseM4v, this.SelectedMp4Extension);
            this.userSettingService.SetUserSetting(UserSettingConstants.AutoNameRemoveUnderscore, this.RemoveUnderscores);
            this.userSettingService.SetUserSetting(UserSettingConstants.AutoNameTitleCase, this.ChangeToTitleCase);
            this.userSettingService.SetUserSetting(UserSettingConstants.RemovePunctuation, this.RemovePunctuation);

            /* Previews */
            this.userSettingService.SetUserSetting(UserSettingConstants.VLCPath, this.VLCPath);

            /* Video */
            this.userSettingService.SetUserSetting(UserSettingConstants.DisableQuickSyncDecoding, this.DisableQuickSyncDecoding);
            this.userSettingService.SetUserSetting(UserSettingConstants.ScalingMode, this.SelectedScalingMode);

            /* System and Logging */
            userSettingService.SetUserSetting(UserSettingConstants.ProcessPriority, this.SelectedPriority);
            userSettingService.SetUserSetting(UserSettingConstants.PreventSleep, this.PreventSleep);
            userSettingService.SetUserSetting(UserSettingConstants.PauseOnLowDiskspace, this.PauseOnLowDiskspace);
            userSettingService.SetUserSetting(UserSettingConstants.Verbosity, this.SelectedVerbosity);
            userSettingService.SetUserSetting(UserSettingConstants.SaveLogWithVideo, this.CopyLogToEncodeDirectory);
            userSettingService.SetUserSetting(UserSettingConstants.SaveLogToCopyDirectory, this.CopyLogToSepcficedLocation);
            userSettingService.SetUserSetting(UserSettingConstants.SaveLogCopyDirectory, this.LogDirectory);
            userSettingService.SetUserSetting(UserSettingConstants.ClearOldLogs, this.ClearOldOlgs);

            /* Advanced */
            userSettingService.SetUserSetting(UserSettingConstants.MainWindowMinimize, this.MinimiseToTray);
            userSettingService.SetUserSetting(UserSettingConstants.ClearCompletedFromQueue, this.ClearQueueOnEncodeCompleted);
            userSettingService.SetUserSetting(UserSettingConstants.PreviewScanCount, this.SelectedPreviewCount);
            userSettingService.SetUserSetting(UserSettingConstants.X264Step, double.Parse(this.SelectedGranulairty, CultureInfo.InvariantCulture));
            userSettingService.SetUserSetting(UserSettingConstants.ShowAdvancedTab, this.ShowAdvancedTab);

            int value;

            if (int.TryParse(this.MinLength.ToString(CultureInfo.InvariantCulture), out value))
            {
                this.userSettingService.SetUserSetting(UserSettingConstants.MinScanDuration, value);
            }

            userSettingService.SetUserSetting(UserSettingConstants.DisableLibDvdNav, this.DisableLibdvdNav);
        }
Beispiel #10
0
        /// <summary>
        /// Override the startup behavior to handle files dropped on the app icon.
        /// </summary>
        /// <param name="e">
        /// The StartupEventArgs.
        /// </param>
        protected override void OnStartup(StartupEventArgs e)
        {
            // We don't support Windows XP / 2003 / 2003 R2 / Vista / 2008
            OperatingSystem os = Environment.OSVersion;

            if (((os.Platform == PlatformID.Win32NT) && (os.Version.Major == 5)) || ((os.Platform == PlatformID.Win32NT) && (os.Version.Major == 6 && os.Version.Minor < 1)))
            {
                MessageBox.Show(HandBrakeWPF.Properties.Resources.OsVersionWarning, HandBrakeWPF.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Warning);
                Application.Current.Shutdown();
                return;
            }

            if (!Environment.Is64BitOperatingSystem)
            {
                MessageBox.Show(HandBrakeWPF.Properties.Resources.OsBitnessWarning, HandBrakeWPF.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Warning);
                Application.Current.Shutdown();
                return;
            }

            if (e.Args.Any(f => f.Equals("--reset")))
            {
                HandBrakeApp.ResetToDefaults();
                Application.Current.Shutdown();
                return;
            }

            if (e.Args.Any(f => f.StartsWith("--recover-queue-ids")))
            {
                string command = e.Args.FirstOrDefault(f => f.StartsWith("--recover-queue-ids"));
                if (!string.IsNullOrEmpty(command))
                {
                    command = command.Replace("--recover-queue-ids=", string.Empty);
                    List <string> processIds = command.Split(',').ToList();
                    StartupOptions.QueueRecoveryIds = processIds;
                }
            }

            if (e.Args.Any(f => f.Equals("--auto-start-queue")))
            {
                StartupOptions.AutoRestartQueue = true;
            }



            // Portable Mode
            if (Portable.IsPortable())
            {
                if (!Portable.Initialise())
                {
                    Application.Current.Shutdown();
                    return;
                }
            }

            // Setup the UI Language
            IUserSettingService userSettingService = IoC.Get <IUserSettingService>();
            string culture = userSettingService.GetUserSetting <string>(UserSettingConstants.UiLanguage);

            if (!string.IsNullOrEmpty(culture))
            {
                InterfaceLanguage language = InterfaceLanguageUtilities.FindInterfaceLanguage(culture);
                if (language != null)
                {
                    CultureInfo ci = new CultureInfo(language.Culture);
                    Thread.CurrentThread.CurrentUICulture = ci;
                }
            }

            int runCounter = userSettingService.GetUserSetting <int>(UserSettingConstants.RunCounter);

            if (!SystemInfo.IsWindows10() && runCounter < 2)
            {
                MessageBox.Show(HandBrakeWPF.Properties.Resources.OldOperatingSystem, HandBrakeWPF.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Warning);
            }

            // Software Rendering
            if (e.Args.Any(f => f.Equals("--force-software-rendering")) || Portable.IsForcingSoftwareRendering() || userSettingService.GetUserSetting <bool>(UserSettingConstants.ForceSoftwareRendering))
            {
                RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
            }

            // Check if the user would like to check for updates AFTER the first run, but only once.
            if (runCounter == 1)
            {
                CheckForUpdateCheckPermission(userSettingService);
            }

            // Increment the counter so we can change startup behavior for the above warning and update check question.
            userSettingService.SetUserSetting(UserSettingConstants.RunCounter, runCounter + 1); // Only display once.

            // App Theme
            DarkThemeMode useDarkTheme = (DarkThemeMode)userSettingService.GetUserSetting <int>(UserSettingConstants.DarkThemeMode);

            if (SystemInfo.IsWindows10())
            {
                ResourceDictionary dark = new ResourceDictionary {
                    Source = new Uri("pack://application:,,,/MahApps.Metro;component/Styles/Themes/Dark.Blue.xaml")
                };
                ResourceDictionary light = new ResourceDictionary {
                    Source = new Uri("pack://application:,,,/MahApps.Metro;component/Styles/Themes/Light.Blue.xaml")
                };

                ResourceDictionary theme = new ResourceDictionary();
                switch (useDarkTheme)
                {
                case DarkThemeMode.System:
                    if (SystemInfo.IsAppsUsingDarkTheme())
                    {
                        theme.Source = new Uri("Themes/Dark.xaml", UriKind.Relative);
                        Application.Current.Resources.MergedDictionaries.Add(theme);
                        Application.Current.Resources.MergedDictionaries.Add(dark);
                    }
                    else if (!SystemParameters.HighContrast)
                    {
                        theme.Source = new Uri("Themes/Light.xaml", UriKind.Relative);
                        Application.Current.Resources.MergedDictionaries.Add(theme);
                        Application.Current.Resources.MergedDictionaries.Add(light);
                    }
                    break;

                case DarkThemeMode.Dark:
                    theme.Source = new Uri("Themes/Dark.xaml", UriKind.Relative);
                    Application.Current.Resources.MergedDictionaries.Add(theme);
                    Application.Current.Resources.MergedDictionaries.Add(dark);
                    break;

                case DarkThemeMode.Light:
                    if (!SystemParameters.HighContrast)
                    {
                        theme.Source = new Uri("Themes/Light.xaml", UriKind.Relative);
                        Application.Current.Resources.MergedDictionaries.Add(theme);
                        Application.Current.Resources.MergedDictionaries.Add(light);
                    }

                    break;
                }
            }

            Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary {
                Source = new Uri("Views/Styles/Styles.xaml", UriKind.Relative)
            });

            // NO-Hardware Mode
            bool noHardware = e.Args.Any(f => f.Equals("--no-hardware")) || (Portable.IsPortable() && !Portable.IsHardwareEnabled());

            // Initialise the Engine
            HandBrakeWPF.Helpers.LogManager.Init();

            try
            {
                HandBrakeInstanceManager.Init(noHardware);
            }
            catch (Exception)
            {
                if (!noHardware)
                {
                    MessageBox.Show(HandBrakeWPF.Properties.Resources.Startup_InitFailed, HandBrakeWPF.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
                }

                throw;
            }

            // Initialise the GUI
            base.OnStartup(e);

            // If we have a file dropped on the icon, try scanning it.
            string[] args = e.Args;
            if (args.Any() && (File.Exists(args[0]) || Directory.Exists(args[0])))
            {
                IMainViewModel mvm = IoC.Get <IMainViewModel>();
                mvm.StartScan(args[0], 0);
            }
        }
Beispiel #11
0
 private void DefaultPlayerCheckedChanged(object sender, EventArgs e)
 {
     UserSettingService.SetUserSetting(UserSettingConstants.DefaultPlayer, defaultPlayer.Checked);
 }
Beispiel #12
0
        /// <summary>
        /// Get's HandBrakes version data from the CLI.
        /// </summary>
        public static void SetCliVersionData()
        {
            string line;

            // 0 = SVN Build / Version
            // 1 = Build Date

            // Get the SHA1 Hash of HandBrakeCLI
            byte[] hash;
            using (Stream stream = File.OpenRead(Path.Combine(Application.StartupPath, "HandBrakeCLI.exe")))
            {
                hash = SHA1.Create().ComputeHash(stream);
            }
            string base64Hash = Convert.ToBase64String(hash);

            // Compare the hash with the last known hash. If it's the same, return.
            if (UserSettingService.GetUserSetting <string>(UserSettingConstants.CliExeHash) == base64Hash)
            {
                return;
            }

            // It's not the same, so start the CLI to get it's version data.
            Process          cliProcess   = new Process();
            ProcessStartInfo handBrakeCli = new ProcessStartInfo("HandBrakeCLI.exe", " -u -v0")
            {
                UseShellExecute        = false,
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                CreateNoWindow         = true
            };

            cliProcess.StartInfo = handBrakeCli;

            try
            {
                cliProcess.Start();

                // Retrieve standard output and report back to parent thread until the process is complete
                TextReader stdOutput = cliProcess.StandardError;

                while (!cliProcess.HasExited)
                {
                    line = stdOutput.ReadLine() ?? string.Empty;
                    Match m        = Regex.Match(line, @"HandBrake ([svnM0-9.]*) \(([0-9]*)\)");
                    Match platform = Regex.Match(line, @"- ([A-Za-z0-9\s ]*) -");

                    if (m.Success)
                    {
                        string version = m.Groups[1].Success ? m.Groups[1].Value : string.Empty;
                        string build   = m.Groups[2].Success ? m.Groups[2].Value : string.Empty;

                        int buildValue;
                        int.TryParse(build, out buildValue);

                        UserSettingService.SetUserSetting(ASUserSettingConstants.HandBrakeBuild, buildValue);
                        UserSettingService.SetUserSetting(ASUserSettingConstants.HandBrakeVersion, version);
                    }

                    if (platform.Success)
                    {
                        UserSettingService.SetUserSetting(ASUserSettingConstants.HandBrakePlatform, platform.Value.Replace("-", string.Empty).Trim());
                    }

                    if (cliProcess.TotalProcessorTime.Seconds > 10) // Don't wait longer than 10 seconds.
                    {
                        Process cli = Process.GetProcessById(cliProcess.Id);
                        if (!cli.HasExited)
                        {
                            cli.Kill();
                        }
                    }
                }

                UserSettingService.SetUserSetting(ASUserSettingConstants.HandBrakeExeHash, base64Hash);
            }
            catch (Exception e)
            {
                UserSettingService.SetUserSetting(ASUserSettingConstants.HandBrakeBuild, string.Empty);
                UserSettingService.SetUserSetting(ASUserSettingConstants.HandBrakePlatform, string.Empty);
                UserSettingService.SetUserSetting(ASUserSettingConstants.HandBrakeVersion, string.Empty);
                UserSettingService.SetUserSetting(ASUserSettingConstants.HandBrakeExeHash, string.Empty);

                ExceptionWindow window = new ExceptionWindow();
                window.Setup("Unable to Initialise HandBrake \nThis error is unrecoverable. Maybe try restarting.", e.ToString());
                window.ShowDialog();

                Application.Exit();
            }
        }
Beispiel #13
0
        /// <summary>
        /// Override the startup behavior to handle files dropped on the app icon.
        /// </summary>
        /// <param name="e">
        /// The StartupEventArgs.
        /// </param>
        protected override void OnStartup(StartupEventArgs e)
        {
            // We don't support Windows XP / 2003 / 2003 R2 / Vista / 2008
            OperatingSystem os = Environment.OSVersion;

            if (((os.Platform == PlatformID.Win32NT) && (os.Version.Major == 5)) || ((os.Platform == PlatformID.Win32NT) && (os.Version.Major == 6 && os.Version.Minor < 1)))
            {
                MessageBox.Show(HandBrakeWPF.Properties.Resources.OsVersionWarning, HandBrakeWPF.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Warning);
                Application.Current.Shutdown();
                return;
            }

            if (!Environment.Is64BitOperatingSystem)
            {
                MessageBox.Show(HandBrakeWPF.Properties.Resources.OsBitnessWarning, HandBrakeWPF.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Warning);
                Application.Current.Shutdown();
                return;
            }

            if (e.Args.Any(f => f.Equals("--reset")))
            {
                HandBrakeApp.ResetToDefaults();
                Application.Current.Shutdown();
                return;
            }

            if (e.Args.Any(f => f.StartsWith("--recover-queue-ids")))
            {
                string command = e.Args.FirstOrDefault(f => f.StartsWith("--recover-queue-ids"));
                if (!string.IsNullOrEmpty(command))
                {
                    command = command.Replace("--recover-queue-ids=", string.Empty);
                    List <string> processIds = command.Split(',').ToList();
                    StartupOptions.QueueRecoveryIds = processIds;
                }
            }

            if (e.Args.Any(f => f.Equals("--auto-start-queue")))
            {
                StartupOptions.AutoRestartQueue = true;
            }

            // Portable Mode
            if (Portable.IsPortable())
            {
                if (!Portable.Initialise())
                {
                    Application.Current.Shutdown();
                    return;
                }
            }

            // Setup the UI Language
            IUserSettingService userSettingService = IoC.Get <IUserSettingService>();
            string culture = userSettingService.GetUserSetting <string>(UserSettingConstants.UiLanguage);

            if (!string.IsNullOrEmpty(culture))
            {
                InterfaceLanguage language = InterfaceLanguageUtilities.FindInterfaceLanguage(culture);
                if (language != null)
                {
                    CultureInfo ci = new CultureInfo(language.Culture);
                    Thread.CurrentThread.CurrentUICulture = ci;
                }
            }

            int oldOsWarningCount = userSettingService.GetUserSetting <int>(UserSettingConstants.OldOsWarning);

            if (!SystemInfo.IsWindows10() && oldOsWarningCount < 2)
            {
                MessageBox.Show(HandBrakeWPF.Properties.Resources.OldOperatingSystem, HandBrakeWPF.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Warning);
                userSettingService.SetUserSetting(UserSettingConstants.OldOsWarning, oldOsWarningCount + 1); // Only display once.
            }

            DarkThemeMode useDarkTheme = (DarkThemeMode)userSettingService.GetUserSetting <int>(UserSettingConstants.DarkThemeMode);

            if (SystemInfo.IsWindows10())
            {
                ResourceDictionary theme = new ResourceDictionary();
                switch (useDarkTheme)
                {
                case DarkThemeMode.System:
                    if (SystemInfo.IsAppsUsingDarkTheme())
                    {
                        theme.Source = new Uri("Themes/Dark.xaml", UriKind.Relative);
                        Application.Current.Resources.MergedDictionaries.Add(theme);
                    }
                    else if (!SystemParameters.HighContrast)
                    {
                        theme.Source = new Uri("Themes/Light.xaml", UriKind.Relative);
                        Application.Current.Resources.MergedDictionaries.Add(theme);
                    }
                    break;

                case DarkThemeMode.Dark:
                    theme.Source = new Uri("Themes/Dark.xaml", UriKind.Relative);
                    Application.Current.Resources.MergedDictionaries.Add(theme);
                    break;

                case DarkThemeMode.Light:
                    if (!SystemParameters.HighContrast)
                    {
                        theme.Source = new Uri("Themes/Light.xaml", UriKind.Relative);
                        Application.Current.Resources.MergedDictionaries.Add(theme);
                    }

                    break;

                default:
                    break;
                }
            }

            // NO-Hardware Mode
            bool noHardware = e.Args.Any(f => f.Equals("--no-hardware")) || (Portable.IsPortable() && !Portable.IsHardwareEnabled());

            // Initialise the Engine
            HandBrakeWPF.Helpers.LogManager.Init();

            try
            {
                HandBrakeInstanceManager.Init(noHardware);
            }
            catch (Exception)
            {
                if (!noHardware)
                {
                    MessageBox.Show(HandBrakeWPF.Properties.Resources.Startup_InitFailed, HandBrakeWPF.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
                }

                throw;
            }

            // Initialise the GUI
            base.OnStartup(e);

            // If we have a file dropped on the icon, try scanning it.
            string[] args = e.Args;
            if (args.Any() && (File.Exists(args[0]) || Directory.Exists(args[0])))
            {
                IMainViewModel mvm = IoC.Get <IMainViewModel>();
                mvm.StartScan(args[0], 0);
            }
        }
Beispiel #14
0
 private void SetSetting(string sName, object sValue)
 {
     _settings?.SetUserSetting(sName, sValue);
 }
Beispiel #15
0
        /// <summary>
        /// The check cli version.
        /// </summary>
        public static void CheckCLIVersion()
        {
            IErrorService errorService = IoC.Get <IErrorService>();

            IUserSettingService userSettingService = IoC.Get <IUserSettingService>();

            string line;

            // 0 = SVN Build / Version
            // 1 = Build Date

            // Get the SHA1 Hash of HandBrakeCLI
            byte[] hash;
            using (Stream stream = File.OpenRead(Path.Combine(Application.StartupPath, "HandBrakeCLI.exe")))
            {
                hash = SHA1.Create().ComputeHash(stream);
            }

            string base64Hash = Convert.ToBase64String(hash);

            // Compare the hash with the last known hash. If it's the same, return.
            if (userSettingService.GetUserSetting <string>(UserSettingConstants.HandBrakeExeHash) == base64Hash)
            {
                return;
            }

            // It's not the same, so start the CLI to get it's version data.
            Process          cliProcess   = new Process();
            ProcessStartInfo handBrakeCli = new ProcessStartInfo(Path.Combine(Application.StartupPath, "HandBrakeCLI.exe"), " -u -v0")
            {
                UseShellExecute        = false,
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                CreateNoWindow         = true
            };

            cliProcess.StartInfo = handBrakeCli;

            try
            {
                cliProcess.Start();

                // Retrieve standard output and report back to parent thread until the process is complete
                bool       success   = false;
                TextReader stdOutput = cliProcess.StandardError;
                while ((line = stdOutput.ReadLine()) != null)
                {
                    Match m = Regex.Match(line, @"HandBrake ([svnM0-9.]*) \(([0-9]*)\)");
                    if (m.Success)
                    {
                        string build = m.Groups[2].Success ? m.Groups[2].Value : string.Empty;

                        int buildValue;
                        int.TryParse(build, out buildValue);

                        userSettingService.SetUserSetting(UserSettingConstants.HandBrakeBuild, buildValue);
                        success = true;
                    }
                }

                while (!cliProcess.HasExited)
                {
                    if (cliProcess.TotalProcessorTime.Seconds > 10) // Don't wait longer than 10 seconds.
                    {
                        Process cli = Process.GetProcessById(cliProcess.Id);
                        if (!cli.HasExited)
                        {
                            cli.Kill();
                        }
                    }
                }

                if (success)
                {
                    userSettingService.SetUserSetting(UserSettingConstants.HandBrakeExeHash, base64Hash);
                }
            }
            catch (Exception e)
            {
                userSettingService.SetUserSetting(UserSettingConstants.HandBrakeBuild, 0);
                userSettingService.SetUserSetting(UserSettingConstants.HandBrakeExeHash, string.Empty);

                errorService.ShowError(
                    "Unable to Initialise HandBrake. This error is unrecoverable.", " Try restarting.", e);
            }
        }
Beispiel #16
0
        /// <summary>
        /// Override the startup behavior to handle files dropped on the app icon.
        /// </summary>
        /// <param name="e">
        /// The StartupEventArgs.
        /// </param>
        protected override void OnStartup(StartupEventArgs e)
        {
            // We don't support Windows earlier than 10.
            if (!SystemInfo.IsWindows10OrLater())
            {
                MessageBox.Show(HandBrakeWPF.Properties.Resources.OsVersionWarning, HandBrakeWPF.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Warning);
                Application.Current.Shutdown();
                return;
            }

            if (!Environment.Is64BitOperatingSystem)
            {
                MessageBox.Show(HandBrakeWPF.Properties.Resources.OsBitnessWarning, HandBrakeWPF.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Warning);
                Application.Current.Shutdown();
                return;
            }

            if (e.Args.Any(f => f.Equals("--reset")))
            {
                HandBrakeApp.ResetToDefaults();
                Application.Current.Shutdown();
                return;
            }

            if (e.Args.Any(f => f.StartsWith("--recover-queue-ids")))
            {
                string command = e.Args.FirstOrDefault(f => f.StartsWith("--recover-queue-ids"));
                if (!string.IsNullOrEmpty(command))
                {
                    command = command.Replace("--recover-queue-ids=", string.Empty);
                    List <string> processIds = command.Split(',').ToList();
                    StartupOptions.QueueRecoveryIds = processIds;
                }
            }

            if (e.Args.Any(f => f.Equals("--auto-start-queue")))
            {
                StartupOptions.AutoRestartQueue = true;
            }

            // Portable Mode
            if (Portable.IsPortable())
            {
                int portableInit = Portable.Initialise();
                if (portableInit != 0)
                {
                    switch (portableInit)
                    {
                    case -1:
                        MessageBox.Show(
                            HandBrakeWPF.Properties.Resources.Portable_IniFileError,
                            HandBrakeWPF.Properties.Resources.Error,
                            MessageBoxButton.OK,
                            MessageBoxImage.Error);
                        break;

                    case -2:
                        MessageBox.Show(
                            HandBrakeWPF.Properties.Resources.Portable_TmpNotWritable,
                            HandBrakeWPF.Properties.Resources.Error,
                            MessageBoxButton.OK,
                            MessageBoxImage.Error);
                        break;

                    case -3:
                        MessageBox.Show(
                            HandBrakeWPF.Properties.Resources.Portable_StorageNotWritable,
                            HandBrakeWPF.Properties.Resources.Error,
                            MessageBoxButton.OK,
                            MessageBoxImage.Error);
                        break;
                    }

                    Application.Current.Shutdown();
                    return;
                }
            }

            // Setup the UI Language
            IUserSettingService userSettingService = IoC.Get <IUserSettingService>();
            string culture = userSettingService.GetUserSetting <string>(UserSettingConstants.UiLanguage);

            if (!string.IsNullOrEmpty(culture))
            {
                InterfaceLanguage language = InterfaceLanguageUtilities.FindInterfaceLanguage(culture);
                if (language != null)
                {
                    CultureInfo ci = new CultureInfo(language.Culture);
                    Thread.CurrentThread.CurrentUICulture = ci;
                }
            }

            int runCounter = userSettingService.GetUserSetting <int>(UserSettingConstants.RunCounter);

            // Software Rendering
            if (e.Args.Any(f => f.Equals("--force-software-rendering")) || Portable.IsForcingSoftwareRendering() || userSettingService.GetUserSetting <bool>(UserSettingConstants.ForceSoftwareRendering))
            {
                RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
            }

            // Check if the user would like to check for updates AFTER the first run, but only once.
            if (runCounter == 1)
            {
                CheckForUpdateCheckPermission(userSettingService);
            }

            // Increment the counter so we can change startup behavior for the above warning and update check question.
            userSettingService.SetUserSetting(UserSettingConstants.RunCounter, runCounter + 1); // Only display once.

            // App Theme
            DarkThemeMode      useDarkTheme = (DarkThemeMode)userSettingService.GetUserSetting <int>(UserSettingConstants.DarkThemeMode);
            ResourceDictionary dark         = new ResourceDictionary {
                Source = new Uri("pack://application:,,,/MahApps.Metro;component/Styles/Themes/Dark.Blue.xaml")
            };
            ResourceDictionary light = new ResourceDictionary {
                Source = new Uri("pack://application:,,,/MahApps.Metro;component/Styles/Themes/Light.Blue.xaml")
            };

            Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary {
                Source = new Uri("Themes/Generic.xaml", UriKind.Relative)
            });
            bool themed = false;

            if (SystemParameters.HighContrast)
            {
                Application.Current.Resources["Ui.Light"]         = new SolidColorBrush(SystemColors.HighlightTextColor);
                Application.Current.Resources["Ui.ContrastLight"] = new SolidColorBrush(SystemColors.ActiveBorderBrush.Color);
                useDarkTheme = DarkThemeMode.None;
            }

            switch (useDarkTheme)
            {
            case DarkThemeMode.System:
                if (SystemInfo.IsAppsUsingDarkTheme())
                {
                    Application.Current.Resources.MergedDictionaries.Add(dark);
                    Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary {
                        Source = new Uri("Themes/Dark.xaml", UriKind.Relative)
                    });
                }
                else
                {
                    Application.Current.Resources.MergedDictionaries.Add(light);
                    Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary {
                        Source = new Uri("Themes/Light.xaml", UriKind.Relative)
                    });
                }

                themed = true;
                break;

            case DarkThemeMode.Dark:
                Application.Current.Resources.MergedDictionaries.Add(dark);
                Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary {
                    Source = new Uri("Themes/Dark.xaml", UriKind.Relative)
                });
                themed = true;
                break;

            case DarkThemeMode.Light:
                Application.Current.Resources.MergedDictionaries.Add(light);
                Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary {
                    Source = new Uri("Themes/Light.xaml", UriKind.Relative)
                });
                themed = true;
                break;

            case DarkThemeMode.None:
                Application.Current.Resources["Ui.Light"]         = new SolidColorBrush(SystemColors.HighlightTextColor);
                Application.Current.Resources["Ui.ContrastLight"] = new SolidColorBrush(SystemColors.ActiveBorderBrush.Color);
                themed = false;
                break;
            }

            Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary {
                Source = new Uri("Views/Styles/Styles.xaml", UriKind.Relative)
            });

            if (themed)
            {
                Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary {
                    Source = new Uri("Views/Styles/ThemedStyles.xaml", UriKind.Relative)
                });
            }

            // NO-Hardware Mode
            bool noHardware = e.Args.Any(f => f.Equals("--no-hardware")) || (Portable.IsPortable() && !Portable.IsHardwareEnabled());

            // Initialise the Engine
            Services.Logging.GlobalLoggingManager.Init();
            HandBrakeInstanceManager.Init(noHardware, userSettingService);

            // Initialise the GUI
            base.OnStartup(e);

            // If we have a file dropped on the icon, try scanning it.
            string[] args = e.Args;
            if (args.Any() && (File.Exists(args[0]) || Directory.Exists(args[0])))
            {
                IMainViewModel mvm = IoC.Get <IMainViewModel>();
                mvm.StartScan(args[0], 0);
            }
        }