// -------------------------------------------------------------------------------------------------------------------- // // This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License. // // // HandBrakes Main Window // // -------------------------------------------------------------------------------------------------------------------- namespace HandBrakeWPF.ViewModels { using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Composition; using System.Diagnostics; using System.IO; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media.Imaging; using Caliburn.Micro; using HandBrake.ApplicationServices; using HandBrake.ApplicationServices.Model; using HandBrake.ApplicationServices.Model.Encoding; using HandBrake.ApplicationServices.Parsing; using HandBrake.ApplicationServices.Services.Interfaces; using HandBrake.ApplicationServices.Utilities; using HandBrakeWPF.Helpers; using HandBrakeWPF.Model; using HandBrakeWPF.ViewModels.Interfaces; using Ookii.Dialogs.Wpf; using HandBrakeWPF.Services.Interfaces; using Image = System.Windows.Controls.Image; /// /// HandBrakes Main Window /// [Export(typeof(IMainViewModel))] public class MainViewModel : ViewModelBase, IMainViewModel { #region Private Variables and Services /// /// The Source Scan Service. /// private readonly IScan scanService; /// /// The Encode Service /// private readonly IEncode encodeService; /// /// The Encode Service /// private readonly IQueueProcessor queueProcessor; /// /// The preset service /// private readonly IPresetService presetService; /// /// The Error Service Backing field. /// private readonly IErrorService errorService; /// /// The Shell View Model /// private readonly IShellViewModel shellViewModel; /// /// Backing field for the user setting service. /// private readonly IUserSettingService userSettingService; /// /// HandBrakes Main Window Title /// private string windowName; /// /// The Source Label /// private string sourceLabel; /// /// The Selected Output Format Backing Field /// private OutputFormat selectedOutputFormat; /// /// Is a MKV file backing field /// private bool isMkv; /// /// The Toolbar Status Label /// private string statusLabel; /// /// Backing field for the scanned source. /// private Source scannedSource; /// /// Backing field for the selected title. /// private Title selectedTitle; /// /// Backing field for duration /// private string duration; /// /// Is Encoding Backing Field /// private bool isEncoding; /// /// An Indicated to show the status window /// private bool showStatusWindow; /// /// Backing field for the selected preset. /// private Preset selectedPreset; #endregion /// /// Initializes a new instance of the class. /// The viewmodel for HandBrakes main window. /// /// /// The window manager. /// /// /// The User Setting Service /// /// /// The scan Service. /// /// /// The encode Service. /// /// /// The preset Service. /// /// /// The Error Service /// /// /// The shell View Model. /// [ImportingConstructor] public MainViewModel(IWindowManager windowManager, IUserSettingService userSettingService, IScan scanService, IEncode encodeService, IPresetService presetService, IErrorService errorService, IShellViewModel shellViewModel) { this.scanService = scanService; this.encodeService = encodeService; this.presetService = presetService; this.errorService = errorService; this.shellViewModel = shellViewModel; this.userSettingService = userSettingService; this.queueProcessor = IoC.Get(); // TODO Instance ID! // Setup Properties this.WindowTitle = "HandBrake"; this.CurrentTask = new EncodeTask(); this.ScannedSource = new Source(); // Setup Events this.scanService.ScanStared += this.ScanStared; this.scanService.ScanCompleted += this.ScanCompleted; this.scanService.ScanStatusChanged += this.ScanStatusChanged; this.queueProcessor.QueueCompleted += this.QueueCompleted; this.queueProcessor.QueuePaused += this.QueuePaused; this.queueProcessor.EncodeService.EncodeStarted += this.EncodeStarted; this.queueProcessor.EncodeService.EncodeStatusChanged += this.EncodeStatusChanged; this.Presets = this.presetService.Presets; } #region View Model Properties /// /// Gets or sets PictureSettingsViewModel. /// public IPictureSettingsViewModel PictureSettingsViewModel { get; set; } /// /// Gets or sets AudioViewModel. /// public IAudioViewModel AudioViewModel { get; set; } /// /// Gets or sets SubtitleViewModel. /// public ISubtitlesViewModel SubtitleViewModel { get; set; } /// /// Gets or sets ChaptersViewModel. /// public IChaptersViewModel ChaptersViewModel { get; set; } /// /// Gets or sets AdvancedViewModel. /// public IAdvancedViewModel AdvancedViewModel { get; set; } /// /// Gets or sets VideoViewModel. /// public IVideoViewModel VideoViewModel { get; set; } /// /// Gets or sets FiltersViewModel. /// public IFiltersViewModel FiltersViewModel { get; set; } #endregion #region Properties /// /// Gets or sets TestProperty. /// public string WindowTitle { get { return this.windowName; } set { if (!Equals(this.windowName, value)) { this.windowName = value; } } } /// /// Gets or sets the Program Status Toolbar Label /// This indicates the status of HandBrake /// public string StatusLabel { get { return string.IsNullOrEmpty(this.statusLabel) ? "Ready" : this.statusLabel; } set { if (!Equals(this.statusLabel, value)) { this.statusLabel = value; this.NotifyOfPropertyChange(() => this.StatusLabel); } } } /// /// Gets SourceToolbarMenu. /// public IEnumerable SourceToolbarMenu { get { // TODO - Find a cleaner way of implementing this BindingList menuItems = new BindingList(); // Folder Menu Item MenuItem folderMenuItem = new MenuItem { Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/HandBrake;component/Views/Images/folder.png")), Width = 16, Height = 16 }, Header = new TextBlock { Text = "Open Folder", Margin = new Thickness(8, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center } }; folderMenuItem.Click += this.folderMenuItem_Click; menuItems.Add(folderMenuItem); // File Menu Item MenuItem fileMenuItem = new MenuItem { Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/HandBrake;component/Views/Images/Movies.png")), Width = 16, Height = 16 }, Header = new TextBlock { Text = "Open File", Margin = new Thickness(8, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center } }; fileMenuItem.Click += this.fileMenuItem_Click; menuItems.Add(fileMenuItem); // File Menu Item MenuItem titleSpecific = new MenuItem { Header = new TextBlock { Text = "Title Specific Scan", Margin = new Thickness(8, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center } }; MenuItem titleSpecificFolder = new MenuItem { Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/HandBrake;component/Views/Images/folder.png")), Width = 16, Height = 16 }, Header = new TextBlock { Text = "Open Folder", Margin = new Thickness(8, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center } }; MenuItem titleSpecificFile = new MenuItem { Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/HandBrake;component/Views/Images/Movies.png")), Width = 16, Height = 16 }, Header = new TextBlock { Text = "Open File", Margin = new Thickness(8, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center } }; titleSpecificFolder.Click += this.titleSpecificFolder_Click; titleSpecificFile.Click += this.titleSpecificFile_Click; titleSpecific.Items.Add(titleSpecificFolder); titleSpecific.Items.Add(titleSpecificFile); menuItems.Add(titleSpecific); // Drives foreach (DriveInformation item in GeneralUtilities.GetDrives()) { MenuItem driveMenuItem = new MenuItem { Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/HandBrake;component/Views/Images/disc_small.png")), Width = 16, Height = 16 }, Header = new TextBlock { Text = string.Format("{0} ({1})", item.RootDirectory, item.VolumeLabel), Margin = new Thickness(8, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center }, Tag = item }; driveMenuItem.Click += this.driveMenuItem_Click; menuItems.Add(driveMenuItem); } return menuItems; } } /// /// Gets or sets Presets. /// public IEnumerable Presets { get; set; } /// /// Gets or sets SelectedPreset. /// public Preset SelectedPreset { get { return this.selectedPreset; } set { this.selectedPreset = value; if (this.SelectedPreset != null) { this.PictureSettingsViewModel.SetPreset(this.SelectedPreset, this.CurrentTask); this.VideoViewModel.SetPreset(this.SelectedPreset, this.CurrentTask); this.FiltersViewModel.SetPreset(this.SelectedPreset, this.CurrentTask); this.AudioViewModel.SetPreset(this.SelectedPreset, this.CurrentTask); this.SubtitleViewModel.SetPreset(this.SelectedPreset, this.CurrentTask); this.ChaptersViewModel.SetPreset(this.SelectedPreset, this.CurrentTask); this.AdvancedViewModel.SetPreset(this.SelectedPreset, this.CurrentTask); } this.NotifyOfPropertyChange(() => this.SelectedPreset); } } /// /// Gets or sets The Current Encode Task that the user is building /// public EncodeTask CurrentTask { get; set; } /// /// Gets or sets the Last Scanned Source /// This object contains information about the scanned source. /// public Source ScannedSource { get { return this.scannedSource; } set { this.scannedSource = value; this.NotifyOfPropertyChange("ScannedSource"); } } /// /// Gets or sets the Source Label /// This indicates the status of scans. /// public string SourceLabel { get { return string.IsNullOrEmpty(this.sourceLabel) ? "Select 'Source' to continue" : this.sourceLabel; } set { if (!Equals(this.sourceLabel, value)) { this.sourceLabel = value; this.NotifyOfPropertyChange("SourceLabel"); } } } /// /// Gets SourceName. /// public string SourceName { get { // The title that is selected has a source name. This means it's part of a batch scan. if (selectedTitle != null && !string.IsNullOrEmpty(selectedTitle.SourceName)) { return Path.GetFileName(selectedTitle.SourceName); } // Check if we have a Folder, if so, check if it's a DVD / Bluray drive and get the label. if (ScannedSource.ScanPath.EndsWith("\\")) { foreach (DriveInformation item in GeneralUtilities.GetDrives()) { if (item.RootDirectory.Contains(this.ScannedSource.ScanPath)) { return item.VolumeLabel; } } } if (Path.GetFileNameWithoutExtension(this.ScannedSource.ScanPath) != "VIDEO_TS") return Path.GetFileNameWithoutExtension(this.ScannedSource.ScanPath); return Path.GetFileNameWithoutExtension(Path.GetDirectoryName(this.ScannedSource.ScanPath)); } } /// /// Gets RangeMode. /// public IEnumerable RangeMode { get { return new List { PointToPointMode.Chapters, PointToPointMode.Seconds, PointToPointMode.Frames }; } } /// /// Gets a value indicating whether ShowTextEntryForPointToPointMode. /// public bool ShowTextEntryForPointToPointMode { get { return this.SelectedPointToPoint != PointToPointMode.Chapters; } } /// /// Gets StartEndRangeItems. /// public IEnumerable StartEndRangeItems { get { if (this.SelectedTitle == null) { return null; } return this.SelectedTitle.Chapters.Select(item => item.ChapterNumber).Select(dummy => dummy).ToList(); } } /// /// Gets Angles. /// public IEnumerable Angles { get { if (this.SelectedTitle == null) { return null; } List items = new List(); for (int i = 1; i <= this.selectedTitle.AngleCount + 1; i++) { items.Add(i); } return items; } } /// /// Gets or sets Duration. /// public string Duration { get { return string.IsNullOrEmpty(duration) ? "--:--:--" : duration; } set { duration = value; this.NotifyOfPropertyChange("Duration"); } } /// /// Gets or sets a value indicating whether IsEncoding. /// public bool IsEncoding { get { return this.isEncoding; } set { this.isEncoding = value; this.NotifyOfPropertyChange(() => this.IsEncoding); } } /// /// Gets or sets a value indicating whether ShowStatusWindow. /// public bool ShowStatusWindow { get { return this.showStatusWindow; } set { this.showStatusWindow = value; this.NotifyOfPropertyChange(() => this.ShowStatusWindow); } } /// /// Gets or sets a value indicating whether IsMkv. /// public bool IsMkv { get { return this.isMkv; } set { this.isMkv = value; this.NotifyOfPropertyChange("IsMkv"); } } /// /// Gets RangeMode. /// public IEnumerable OutputFormats { get { return new List { OutputFormat.Mp4, OutputFormat.Mkv }; } } #endregion #region Properties for Settings /// /// Gets or sets Destination. /// public string Destination { get { return this.CurrentTask.Destination; } set { this.CurrentTask.Destination = value; this.NotifyOfPropertyChange(() => this.Destination); } } /// /// Gets or sets SelectedTitle. /// public Title SelectedTitle { get { return this.selectedTitle; } set { if (!Equals(this.selectedTitle, value)) { this.selectedTitle = value; if (selectedTitle == null) { return; } // Use the Path on the Title, or the Source Scan path if one doesn't exist. this.CurrentTask.Source = !string.IsNullOrEmpty(this.selectedTitle.SourceName) ? this.selectedTitle.SourceName : this.ScannedSource.ScanPath; this.CurrentTask.Title = value.TitleNumber; this.NotifyOfPropertyChange(() => this.StartEndRangeItems); this.NotifyOfPropertyChange(() => this.SelectedTitle); this.NotifyOfPropertyChange(() => this.Angles); // Default the Start and End Point dropdowns this.SelectedStartPoint = 1; this.SelectedEndPoint = selectedTitle.Chapters.Last().ChapterNumber; this.SelectedPointToPoint = PointToPointMode.Chapters; this.SelectedAngle = 1; if (this.UserSettingService.GetUserSetting(UserSettingConstants.AutoNaming)) { this.Destination = AutoNameHelper.AutoName(this.CurrentTask, this.SourceName); } this.NotifyOfPropertyChange(() => this.CurrentTask); this.Duration = selectedTitle.Duration.ToString(); // Setup the tab controls this.SetupTabs(); } } } /// /// Gets or sets SelectedAngle. /// public int SelectedAngle { get { return this.CurrentTask.StartPoint; } set { this.CurrentTask.Angle = value; this.NotifyOfPropertyChange(() => this.SelectedAngle); } } /// /// Gets or sets SelectedStartPoint. /// public int SelectedStartPoint { get { return this.CurrentTask.StartPoint; } set { this.CurrentTask.StartPoint = value; this.NotifyOfPropertyChange(() => this.SelectedStartPoint); this.Duration = this.DurationCalculation(); if (this.UserSettingService.GetUserSetting(UserSettingConstants.AutoNaming)) { this.Destination = AutoNameHelper.AutoName(this.CurrentTask, this.SourceName); } } } /// /// Gets or sets SelectedEndPoint. /// public int SelectedEndPoint { get { return this.CurrentTask.EndPoint; } set { this.CurrentTask.EndPoint = value; this.NotifyOfPropertyChange(() => this.SelectedEndPoint); this.Duration = this.DurationCalculation(); if (this.UserSettingService.GetUserSetting(UserSettingConstants.AutoNaming)) { this.Destination = AutoNameHelper.AutoName(this.CurrentTask, this.SourceName); } } } /// /// Gets or sets SelectedPointToPoint. /// public PointToPointMode SelectedPointToPoint { get { return this.CurrentTask.PointToPointMode; } set { this.CurrentTask.PointToPointMode = value; this.NotifyOfPropertyChange(() => SelectedPointToPoint); this.NotifyOfPropertyChange(() => ShowTextEntryForPointToPointMode); if (value == PointToPointMode.Chapters && this.SelectedTitle != null) { this.SelectedStartPoint = 1; this.SelectedEndPoint = selectedTitle.Chapters.Last().ChapterNumber; } } } /// /// Gets or sets SelectedOutputFormat. /// public OutputFormat SelectedOutputFormat { get { return this.selectedOutputFormat; } set { this.selectedOutputFormat = value; this.CurrentTask.OutputFormat = value; this.NotifyOfPropertyChange(() => SelectedOutputFormat); this.NotifyOfPropertyChange(() => this.CurrentTask.OutputFormat); this.NotifyOfPropertyChange(() => IsMkv); this.SetExtension(string.Format(".{0}", this.selectedOutputFormat.ToString().ToLower())); // TODO, tidy up this.VideoViewModel.RefreshTask(); this.AudioViewModel.RefreshTask(); } } #endregion #region Load and Shutdown Handling /// /// Initialise this view model. /// public override void OnLoad() { // Check the CLI Executable. CliCheckHelper.CheckCLIVersion(); // Perform an update check if required UpdateCheckHelper.PerformStartupUpdateCheck(); // Setup the presets. if (this.presetService.CheckIfPresetsAreOutOfDate()) if (!this.userSettingService.GetUserSetting(UserSettingConstants.PresetNotification)) this.errorService.ShowMessageBox("HandBrake has determined your built-in presets are out of date... These presets will now be updated.", "Preset Update", MessageBoxButton.OK, MessageBoxImage.Information); this.SelectedPreset = this.presetService.DefaultPreset; } /// /// Shutdown this View /// public void Shutdown() { // Unsubscribe from Events. this.scanService.ScanStared -= this.ScanStared; this.scanService.ScanCompleted -= this.ScanCompleted; this.scanService.ScanStatusChanged -= this.ScanStatusChanged; this.queueProcessor.QueueCompleted -= this.QueueCompleted; this.queueProcessor.QueuePaused -= this.QueuePaused; this.queueProcessor.EncodeService.EncodeStarted -= this.EncodeStarted; this.queueProcessor.EncodeService.EncodeStatusChanged -= this.EncodeStatusChanged; } /// /// Handle the Window Closing Event and warn the user if an encode is in-progress /// /// /// The CancelEventArgs. /// public void HandleWindowClosing(CancelEventArgs e) { if (this.encodeService.IsEncoding) { MessageBoxResult result = this.errorService.ShowMessageBox("HandBrake is currently encoding. Closing now will abort your encode.\nAre you sure you wish to exit?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (result == MessageBoxResult.No) { e.Cancel = true; } else { this.encodeService.Stop(); } } } #endregion #region Menu and Taskbar /// /// Open the About Window /// public void OpenAboutApplication() { this.WindowManager.ShowWindow(IoC.Get()); } /// /// Open the Options Window /// public void OpenOptionsWindow() { this.shellViewModel.DisplayWindow(ShellWindow.OptionsWindow); } /// /// Open the Log Window /// public void OpenLogWindow() { this.WindowManager.ShowWindow(IoC.Get()); } /// /// Open the Queue Window. /// public void OpenQueueWindow() { this.WindowManager.ShowWindow(IoC.Get()); } /// /// Open the Queue Window. /// public void OpenPreviewWindow() { IPreviewViewModel viewModel = IoC.Get(); this.WindowManager.ShowWindow(viewModel); viewModel.Task = this.CurrentTask; } /// /// Launch the Help pages. /// public void LaunchHelp() { Process.Start("https://trac.handbrake.fr/wiki/HandBrakeGuide"); } /// /// Check for Updates. /// public void CheckForUpdates() { UpdateCheckHelper.CheckForUpdates(); } /// /// Add the current task to the queue. /// public void AddToQueue() { if (this.ScannedSource == null || string.IsNullOrEmpty(this.ScannedSource.ScanPath) || this.ScannedSource.Titles.Count == 0) { this.errorService.ShowMessageBox("You must first scan a source and setup your job before adding to the queue.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } QueueTask task = new QueueTask { Task = new EncodeTask(this.CurrentTask) }; this.queueProcessor.QueueManager.Add(task); if (!this.IsEncoding) { this.StatusLabel = string.Format("{0} Encodes Pending", this.queueProcessor.QueueManager.Count); } } /// /// Add all Items to the queue /// public void AddAllToQueue() { if (this.ScannedSource == null || this.ScannedSource.Titles == null || this.ScannedSource.Titles.Count == 0) { this.errorService.ShowMessageBox("You must first scan a source and setup your job before adding to the queue.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (!AutoNameHelper.IsAutonamingEnabled()) { this.errorService.ShowMessageBox("You must turn on automatic file naming in preferences before you can add to the queue.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } foreach (Title title in this.ScannedSource.Titles) { this.SelectedTitle = title; this.AddToQueue(); } } /// /// Folder Scan /// public void FolderScan() { VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog { Description = "Please select a folder.", UseDescriptionForTitle = true }; dialog.ShowDialog(); this.StartScan(dialog.SelectedPath, 0); } /// /// File Scan /// public void FileScan() { VistaOpenFileDialog dialog = new VistaOpenFileDialog { Filter = "All files (*.*)|*.*" }; dialog.ShowDialog(); this.StartScan(dialog.FileName, 0); } /// /// Folder Scan /// public void FolderScanTitleSpecific() { VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog { Description = "Please select a folder.", UseDescriptionForTitle = true }; dialog.ShowDialog(); if (string.IsNullOrEmpty(dialog.SelectedPath)) { return; } ITitleSpecificViewModel titleSpecificView = IoC.Get(); this.WindowManager.ShowDialog(titleSpecificView); if (titleSpecificView.SelectedTitle.HasValue) { this.StartScan(dialog.SelectedPath, titleSpecificView.SelectedTitle.Value); } } /// /// File Scan /// public void FileScanTitleSpecific() { VistaOpenFileDialog dialog = new VistaOpenFileDialog { Filter = "All files (*.*)|*.*" }; dialog.ShowDialog(); if (string.IsNullOrEmpty(dialog.FileName)) { return; } ITitleSpecificViewModel titleSpecificView = IoC.Get(); this.WindowManager.ShowDialog(titleSpecificView); if (titleSpecificView.SelectedTitle.HasValue) { this.StartScan(dialog.FileName, titleSpecificView.SelectedTitle.Value); } } /// /// Cancel a Scan /// public void CancelScan() { this.scanService.Stop(); } /// /// Start an Encode /// public void StartEncode() { // Check if we already have jobs, and if we do, just start the queue. if (this.queueProcessor.QueueManager.Count != 0) { this.queueProcessor.Start(); return; } // Otherwise, perform Santiy Checking then add to the queue and start if everything is ok. if (this.ScannedSource == null || this.CurrentTask == null) { this.errorService.ShowMessageBox("You must first scan a source.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (string.IsNullOrEmpty(this.Destination)) { this.errorService.ShowMessageBox("The Destination field was empty.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (this.queueProcessor.IsProcessing) { this.errorService.ShowMessageBox("HandBrake is already encoding.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (File.Exists(this.Destination)) { MessageBoxResult result = this.errorService.ShowMessageBox("The current file already exists, do you wish to overwrite it?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.No) { return; } } // Create the Queue Task and Start Processing QueueTask task = new QueueTask { Task = new EncodeTask(this.CurrentTask), CustomQuery = false }; this.queueProcessor.QueueManager.Add(task); this.queueProcessor.Start(); this.IsEncoding = true; } /// /// Pause an Encode /// public void PauseEncode() { this.queueProcessor.Pause(); } /// /// Stop an Encode. /// public void StopEncode() { this.encodeService.Stop(); } /// /// Shutdown the Application /// public void ExitApplication() { Application.Current.Shutdown(); } /// /// DEBUG: Show CLI Query for settings+6 /// public void ShowCliQuery() { this.errorService.ShowMessageBox( QueryGeneratorUtility.GenerateQuery(this.CurrentTask), "CLI Query", MessageBoxButton.OK, MessageBoxImage.Information); } #endregion #region Main Window Public Methods /// /// Support dropping a file onto the main window to scan. /// /// /// The DragEventArgs. /// public void FilesDroppedOnWindow(DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] fileNames = e.Data.GetData(DataFormats.FileDrop, true) as string[]; if (fileNames != null && fileNames.Any() && (File.Exists(fileNames[0]) || Directory.Exists(fileNames[0])) ) { this.StartScan(fileNames[0], 0); } } e.Handled = true; } /// /// The Destination Path /// public void BrowseDestination() { VistaSaveFileDialog dialog = new VistaSaveFileDialog { Filter = "mp4|*.mp4;*.m4v|mkv|*.mkv", AddExtension = true, OverwritePrompt = true, DefaultExt = ".mp4" }; dialog.ShowDialog(); if (!string.IsNullOrEmpty(dialog.FileName)) { switch (Path.GetExtension(dialog.FileName)) { case ".mkv": this.SelectedOutputFormat = OutputFormat.Mkv; break; case ".mp4": this.SelectedOutputFormat = OutputFormat.Mp4; break; case ".m4v": this.SelectedOutputFormat = OutputFormat.M4V; break; } this.Destination = dialog.FileName; this.NotifyOfPropertyChange(() => this.CurrentTask); } } /// /// Add a Preset /// public void PresetAdd() { IAddPresetViewModel presetViewModel = IoC.Get(); presetViewModel.Setup(this.CurrentTask); this.WindowManager.ShowWindow(presetViewModel); } /// /// Remove a Preset /// public void PresetRemove() { if (this.selectedPreset != null) { this.presetService.Remove(this.selectedPreset); } else { MessageBox.Show("Please select a preset.", "Presets", MessageBoxButton.OK, MessageBoxImage.Warning); } } /// /// Set a default preset /// public void PresetSetDefault() { if (this.selectedPreset != null) { this.presetService.SetDefault(this.selectedPreset); MessageBox.Show(string.Format("New Default Preset Set: {0}", this.selectedPreset.Name), "Presets", MessageBoxButton.OK, MessageBoxImage.Warning); } else { MessageBox.Show("Please select a preset.", "Presets", MessageBoxButton.OK, MessageBoxImage.Warning); } } /// /// Import a Preset /// public void PresetImport() { VistaOpenFileDialog dialog = new VistaOpenFileDialog { Filter = "Plist (*.plist)|*.plist", CheckFileExists = true }; dialog.ShowDialog(); string filename = dialog.FileName; if (!string.IsNullOrEmpty(filename)) { Preset preset = PlistUtility.Import(filename); if (this.presetService.CheckIfPresetExists(preset.Name)) { if (!presetService.CanUpdatePreset(preset.Name)) { MessageBox.Show( "You can not import a preset with the same name as a built-in preset.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } MessageBoxResult result = MessageBox.Show( "This preset appears to already exist. Would you like to overwrite it?", "Overwrite preset?", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (result == MessageBoxResult.Yes) { presetService.Update(preset); } } else { presetService.Add(preset); } this.NotifyOfPropertyChange(() => this.Presets); } } /// /// Export a Preset /// public void PresetExport() { VistaSaveFileDialog savefiledialog = new VistaSaveFileDialog { Filter = "plist|*.plist", CheckPathExists = true }; if (this.selectedPreset != null) { savefiledialog.ShowDialog(); string filename = savefiledialog.FileName; if (filename != null) { PlistUtility.Export(savefiledialog.FileName, this.selectedPreset); } } else { MessageBox.Show("Please select a preset.", "Presets", MessageBoxButton.OK, MessageBoxImage.Warning); } } /// /// Reset built-in presets /// public void PresetReset() { this.presetService.UpdateBuiltInPresets(); this.NotifyOfPropertyChange("Presets"); this.SelectedPreset = this.presetService.DefaultPreset; } /// /// Set the selected preset. /// /// /// The RoutedPropertyChangedEventArgs. /// public void SetSelectedPreset(RoutedPropertyChangedEventArgs e) { this.SelectedPreset = e.NewValue as Preset; } #endregion #region Private Methods /// /// Start a Scan /// /// /// The filename. /// /// /// The title. /// private void StartScan(string filename, int title) { // TODO // 1. Disable GUI. this.scanService.Scan(filename, title, this.UserSettingService.GetUserSetting(ASUserSettingConstants.PreviewScanCount)); } /// /// Make sure the correct file extension is set based on user preferences and setup the GUI for the file container selected. /// /// /// The new extension. /// private void SetExtension(string newExtension) { // Make sure the output extension is set correctly based on the users preferences and selection. if (newExtension == ".mp4" || newExtension == ".m4v") { switch (this.UserSettingService.GetUserSetting(UserSettingConstants.UseM4v)) { case 0: // Auto newExtension = this.CurrentTask.RequiresM4v ? ".m4v" : ".mp4"; break; case 1: // MP4 newExtension = ".mp4"; break; case 2: // M4v newExtension = ".m4v"; break; } this.IsMkv = false; } // Now disable controls that are not required. The Following are for MP4 only! if (newExtension == ".mkv") { this.IsMkv = true; this.CurrentTask.LargeFile = false; this.CurrentTask.OptimizeMP4 = false; this.CurrentTask.IPod5GSupport = false; } // Update The browse file extension display if (Path.HasExtension(newExtension)) { this.Destination = Path.ChangeExtension(this.Destination, newExtension); } // Update the UI Display this.NotifyOfPropertyChange(() => this.CurrentTask); } /// /// Setup the UI tabs. Passes in any relevant models for setup. /// private void SetupTabs() { // Setup the Tabs if (this.selectedTitle != null) { this.PictureSettingsViewModel.SetSource(this.SelectedTitle, this.SelectedPreset, this.CurrentTask); this.VideoViewModel.SetSource(this.SelectedTitle, this.SelectedPreset, this.CurrentTask); this.FiltersViewModel.SetSource(this.SelectedTitle, this.SelectedPreset, this.CurrentTask); this.AudioViewModel.SetSource(this.SelectedTitle, this.SelectedPreset, this.CurrentTask); this.SubtitleViewModel.SetSource(this.SelectedTitle, this.SelectedPreset, this.CurrentTask); this.ChaptersViewModel.SetSource(this.SelectedTitle, this.SelectedPreset, this.CurrentTask); this.AdvancedViewModel.SetSource(this.SelectedTitle, this.SelectedPreset, this.CurrentTask); } } /// /// Calculate the duration between the end and start point /// /// /// The duration calculation. /// private string DurationCalculation() { if (this.selectedTitle == null) { return "--:--:--"; } double startEndDuration = this.SelectedEndPoint - this.SelectedStartPoint; switch (this.SelectedPointToPoint) { case PointToPointMode.Chapters: return this.SelectedTitle.CalculateDuration(this.SelectedStartPoint, this.SelectedEndPoint).ToString(); case PointToPointMode.Seconds: return TimeSpan.FromSeconds(startEndDuration).ToString(); case PointToPointMode.Frames: startEndDuration = startEndDuration / selectedTitle.Fps; return TimeSpan.FromSeconds(startEndDuration).ToString(); } return "--:--:--"; } #endregion #region Event Handlers /// /// Handle the Scan Status Changed Event. /// /// /// The Sender /// /// /// The EventArgs /// private void ScanStatusChanged(object sender, HandBrake.ApplicationServices.EventArgs.ScanProgressEventArgs e) { this.SourceLabel = "Scanning Title " + e.CurrentTitle + " of " + e.Titles; this.StatusLabel = "Scanning Title " + e.CurrentTitle + " of " + e.Titles; } /// /// Handle the Scan Completed Event /// /// /// The Sender /// /// /// The EventArgs /// private void ScanCompleted(object sender, HandBrake.ApplicationServices.EventArgs.ScanCompletedEventArgs e) { Execute.OnUIThread(() => { if (e.Successful) { this.scanService.SouceData.CopyTo(this.ScannedSource); this.NotifyOfPropertyChange("ScannedSource"); this.NotifyOfPropertyChange("ScannedSource.Titles"); this.SelectedTitle = this.ScannedSource.Titles.FirstOrDefault(t => t.MainTitle) ?? this.ScannedSource.Titles.FirstOrDefault(); this.JobContextService.CurrentSource = this.ScannedSource; this.JobContextService.CurrentTask = this.CurrentTask; this.SetupTabs(); this.ShowStatusWindow = false; } this.SourceLabel = "Scan Completed"; this.StatusLabel = "Scan Completed"; }); } /// /// Handle the Scan Started Event /// /// /// The Sender /// /// /// The EventArgs /// private void ScanStared(object sender, EventArgs e) { Execute.OnUIThread( () => { this.StatusLabel = "Scanning source, please wait..."; this.ShowStatusWindow = true; }); // TODO - Disable relevant parts of the UI. } /// /// The Encode Status has changed Handler /// /// /// The Sender /// /// /// The Encode Progress Event Args /// private void EncodeStatusChanged(object sender, HandBrake.ApplicationServices.EventArgs.EncodeProgressEventArgs e) { Execute.OnUIThread( () => { this.StatusLabel = string.Format( "{0:00.00}%, FPS: {1:000.0}, Avg FPS: {2:000.0}, Time Remaining: {3}, Elapsed: {4:hh\\:mm\\:ss}, Pending Jobs {5}", e.PercentComplete, e.CurrentFrameRate, e.AverageFrameRate, e.EstimatedTimeLeft, e.ElapsedTime, this.queueProcessor.QueueManager.Count); }); } /// /// Encode Started Handler /// /// /// The Sender /// /// /// The EventArgs /// private void EncodeStarted(object sender, EventArgs e) { Execute.OnUIThread( () => { this.StatusLabel = "Preparing to encode ..."; this.IsEncoding = true; }); // TODO Handle Updating the UI } /// /// The Queue has been paused handler /// /// /// The Sender /// /// /// The EventArgs /// private void QueuePaused(object sender, EventArgs e) { this.IsEncoding = false; // TODO Handle Updating the UI } /// /// The Queue has completed handler /// /// /// The Sender /// /// /// The EventArgs /// private void QueueCompleted(object sender, EventArgs e) { this.IsEncoding = false; Execute.OnUIThread( () => { this.StatusLabel = "Queue Finished"; this.IsEncoding = false; }); // TODO Handle Updating the UI } /// /// Drive Scan /// /// /// The sender. /// /// /// The RoutedEventArgs. /// private void driveMenuItem_Click(object sender, RoutedEventArgs e) { MenuItem item = e.OriginalSource as MenuItem; if (item != null) { this.StartScan(((DriveInformation)item.Tag).RootDirectory, 0); } } /// /// File Scan /// /// /// The sender. /// /// /// The RoutedEventArgs. /// private void fileMenuItem_Click(object sender, RoutedEventArgs e) { this.FileScan(); } /// /// Folder Scan /// /// /// The sender. /// /// /// The RoutedEventArgs. /// private void folderMenuItem_Click(object sender, RoutedEventArgs e) { this.FolderScan(); } /// /// Title Specific Scan for File /// /// /// The sender. /// /// /// The e. /// private void titleSpecificFile_Click(object sender, RoutedEventArgs e) { this.FileScanTitleSpecific(); } /// /// Title Specific Scan for folder /// /// /// The sender. /// /// /// The e. /// private void titleSpecificFolder_Click(object sender, RoutedEventArgs e) { this.FolderScanTitleSpecific(); } #endregion } }